﻿
// This file implements the TableControl, TableControlRow, and RecordControl classes for the 
// ShowGasolineraTable.aspx page.  The Row or RecordControl classes are the 
// ideal place to add code customizations. For example, you can override the LoadData, 
// CreateWhereClause, DataBind, SaveData, GetUIData, and Validate methods.

#region "Using statements"    

using Microsoft.VisualBasic;
using BaseClasses.Web.UI.WebControls;
using System;
using System.Collections;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaseClasses;
using BaseClasses.Data;
using BaseClasses.Utils;
using ReportTools.ReportCreator;
using ReportTools.Shared;

        
using EnGasAdoAPP.Business;
using EnGasAdoAPP.Data;
using EnGasAdoAPP.UI;
using EnGasAdoAPP;
		

#endregion

  
namespace EnGasAdoAPP.UI.Controls.ShowGasolineraTable
{
  

#region "Section 1: Place your customizations here."

    
public class GasolineraTableControlRow : BaseGasolineraTableControlRow
{
      
        // The BaseGasolineraTableControlRow implements code for a ROW within the
        // the GasolineraTableControl table.  The BaseGasolineraTableControlRow implements the DataBind and SaveData methods.
        // The loading of data is actually performed by the LoadData method in the base class of GasolineraTableControl.

        // This is the ideal place to add your code customizations. For example, you can override the DataBind, 
        // SaveData, GetUIData, and Validate methods.
        
}

  

public class GasolineraTableControl : BaseGasolineraTableControl
{
    // The BaseGasolineraTableControl class implements the LoadData, DataBind, CreateWhereClause
    // and other methods to load and display the data in a table control.

    // This is the ideal place to add your code customizations. You can override the LoadData and CreateWhereClause,
    // The GasolineraTableControlRow class offers another place where you can customize
    // the DataBind, GetUIData, SaveData and Validate methods specific to each row displayed on the table.

}

  
//public class Marca_gasolineraRecordControl : BaseMarca_gasolineraRecordControl
//{
//      
//        // The BaseMarca_gasolineraRecordControl implements the LoadData, DataBind and other
//        // methods to load and display the data in a table control.
//
//        // This is the ideal place to add your code customizations. For example, you can override the LoadData, 
//        // CreateWhereClause, DataBind, SaveData, GetUIData, and Validate methods.
//        
//}
//

  

#endregion

  

#region "Section 2: Do not modify this section."
    
    
// Base class for the GasolineraTableControlRow control on the ShowGasolineraTable page.
// Do not modify this class. Instead override any method in GasolineraTableControlRow.
public class BaseGasolineraTableControlRow : EnGasAdoAPP.UI.BaseApplicationRecordControl
{
        public BaseGasolineraTableControlRow()
        {
            this.Init += Control_Init;
            this.Load += Control_Load;
            this.PreRender += Control_PreRender;
            this.EvaluateFormulaDelegate = new DataSource.EvaluateFormulaDelegate(this.EvaluateFormula);
        }

        // To customize, override this method in GasolineraTableControlRow.
        protected virtual void Control_Init(object sender, System.EventArgs e)
        {
                
            this.ClearControlsFromSession();
        }

        // To customize, override this method in GasolineraTableControlRow.
        protected virtual void Control_Load(object sender, System.EventArgs e)
        {
        
            //Call LoadFocusScripts from repeater so that onfocus attribute could be added to elements
            this.Page.LoadFocusScripts(this);
        
              // Show confirmation message on Click
              this.GasolineraRowDeleteButton.Attributes.Add("onClick", "return (confirm('" + ((BaseApplicationPage)this.Page).GetResourceValue("DeleteRecordConfirm", "EnGasAdoAPP") + "'));");   
        
            // Register the event handlers.
          
              this.GasolineraRowCopyButton.Click += new ImageClickEventHandler(GasolineraRowCopyButton_Click);
        
              this.GasolineraRowDeleteButton.Click += new ImageClickEventHandler(GasolineraRowDeleteButton_Click);
        
              this.GasolineraRowEditButton.Click += new ImageClickEventHandler(GasolineraRowEditButton_Click);
        
              this.GasolineraRowViewButton.Click += new ImageClickEventHandler(GasolineraRowViewButton_Click);
        
        }

        public virtual void LoadData()  
        {
            // Load the data from the database into the DataSource Gasolinera record.
            // It is better to make changes to functions called by LoadData such as
            // CreateWhereClause, rather than making changes here.
            
        
            // The RecordUniqueId is set the first time a record is loaded, and is
            // used during a PostBack to load the record.
            if (this.RecordUniqueId != null && this.RecordUniqueId.Length > 0) {
              
                this.DataSource = GasolineraTable.GetRecord(this.RecordUniqueId, true);
              
                return;
            }
      
            // Since this is a row in the table, the data for this row is loaded by the 
            // LoadData method of the BaseGasolineraTableControl when the data for the entire
            // table is loaded.
            
            this.DataSource = new GasolineraRecord();
            
        }

        public override void DataBind()
        {
            // The DataBind method binds the user interface controls to the values
            // from the database record.  To do this, it calls the Set methods for 
            // each of the field displayed on the webpage.  It is better to make 
            // changes in the Set methods, rather than making changes here.
            
            base.DataBind();
            
            // Make sure that the DataSource is initialized.
            
            if (this.DataSource == null) {
                return;
            }
              
    
            // LoadData for DataSource for chart and report if they exist
          

            // Call the Set methods for each controls on the panel
        
                SetDescripcion();
                
                
                
                
                
                SetGEOLocalisacion();
                Setlatitud();
                Setlongitud();
                SetNombre_Gasolinera();
                SetObservaciones();

      

            this.IsNewRecord = true;
          
            if (this.DataSource.IsCreated) {
                this.IsNewRecord = false;
              
                this.RecordUniqueId = this.DataSource.GetID().ToXmlString();
            }
          

            // Now load data for each record and table child UI controls.
            // Ordering is important because child controls get 
            // their parent ids from their parent UI controls.
            bool shouldResetControl = false;
            if (shouldResetControl) { }; // prototype usage to void compiler warnings
            
        }

        
        public virtual void SetDescripcion()
        {
            
                    
            // Set the Descripcion Literal on the webpage with value from the
            // Gasolinera database record.

            // this.DataSource is the Gasolinera record retrieved from the database.
            // this.Descripcion is the ASP:Literal on the webpage.
                  
            if (this.DataSource != null && this.DataSource.DescripcionSpecified) {
                								
                // If the Descripcion is non-NULL, then format the value.
                // The Format method will use the Display Format
                                  string formattedValue = this.DataSource.Format(GasolineraTable.Descripcion);
                                
                formattedValue = HttpUtility.HtmlEncode(formattedValue);
                this.Descripcion.Text = formattedValue;
                   
            } 
            
            else {
            
                // Descripcion is NULL in the database, so use the Default Value.  
                // Default Value could also be NULL.
        
                this.Descripcion.Text = GasolineraTable.Descripcion.Format(GasolineraTable.Descripcion.DefaultValue);
            		
            }
            
            // If the Descripcion is NULL or blank, then use the value specified  
            // on Properties.
            if (this.Descripcion.Text == null ||
                this.Descripcion.Text.Trim().Length == 0) {
                // Set the value specified on the Properties.
                this.Descripcion.Text = "&nbsp;";
            }
                  
        }
                
        public virtual void SetGEOLocalisacion()
        {
            
                    
            // Set the GEOLocalisacion Literal on the webpage with value from the
            // Gasolinera database record.

            // this.DataSource is the Gasolinera record retrieved from the database.
            // this.GEOLocalisacion is the ASP:Literal on the webpage.
                  
            if (this.DataSource != null && this.DataSource.GEOLocalisacionSpecified) {
                								
                // If the GEOLocalisacion is non-NULL, then format the value.
                // The Format method will use the Display Format
                                  string formattedValue = this.DataSource.Format(GasolineraTable.GEOLocalisacion);
                                
                formattedValue = HttpUtility.HtmlEncode(formattedValue);
                if(formattedValue != null){
                    int popupThreshold = (int)(100);
                              
                    int maxLength = formattedValue.Length;
                    if (maxLength > (int)(100)){
                        // Truncate based on FieldMaxLength on Properties.
                        maxLength = (int)(100);
                        
                    }
                                
                              
                    // For fields values larger than the PopupTheshold on Properties, display a popup.
                    if (formattedValue.Length >= popupThreshold) {
                      
                        String name = HttpUtility.HtmlEncode(GasolineraTable.GEOLocalisacion.Name);

                        if (!HttpUtility.HtmlEncode("%ISD_DEFAULT%").Equals("%ISD_DEFAULT%")) {
                           name = HttpUtility.HtmlEncode(this.Page.GetResourceValue("%ISD_DEFAULT%"));
                        }

                        formattedValue = "<a onclick=\'gPersist=true;\' onmouseout=\'detailRolloverPopupClose();\' " +
                            "onmouseover=\'SaveMousePosition(event); delayRolloverPopup(\"PageMethods.GetRecordFieldValue(\\\"" + "NULL" + "\\\", \\\"EnGasAdoAPP.Business.GasolineraTable, App_Code\\\",\\\"" +
                              (HttpUtility.UrlEncode(this.DataSource.GetID().ToString())).Replace("\\","\\\\\\\\") + "\\\", \\\"GEOLocalisacion\\\", \\\"GEOLocalisacion\\\", \\\"" +NetUtils.EncodeStringForHtmlDisplay(name.Substring(0, name.Length))+" \\\"," +
                        " false, 200," +
                            " 300, true, PopupDisplayWindowCallBackWith20);\", 500);'>" + NetUtils.EncodeStringForHtmlDisplay(formattedValue.Substring(0, maxLength));
                      
                        if (maxLength == (int)(100))
                            {
                            formattedValue = formattedValue + "..." + "</a>";
                        }
                        else
                        {
                            formattedValue = formattedValue + "</a>";
                            
                        }
                    }
                    else{
                        if (maxLength == (int)(100)) {
                          formattedValue = NetUtils.EncodeStringForHtmlDisplay(formattedValue.Substring(0,maxLength));
                          formattedValue = formattedValue + "...";
                        }
                        
                    }
                }
                
                this.GEOLocalisacion.Text = formattedValue;
                   
            } 
            
            else {
            
                // GEOLocalisacion is NULL in the database, so use the Default Value.  
                // Default Value could also be NULL.
        
                this.GEOLocalisacion.Text = GasolineraTable.GEOLocalisacion.Format(GasolineraTable.GEOLocalisacion.DefaultValue);
            		
            }
            
            // If the GEOLocalisacion is NULL or blank, then use the value specified  
            // on Properties.
            if (this.GEOLocalisacion.Text == null ||
                this.GEOLocalisacion.Text.Trim().Length == 0) {
                // Set the value specified on the Properties.
                this.GEOLocalisacion.Text = "&nbsp;";
            }
                  
        }
                
        public virtual void Setlatitud()
        {
            
                    
            // Set the latitud Literal on the webpage with value from the
            // Gasolinera database record.

            // this.DataSource is the Gasolinera record retrieved from the database.
            // this.latitud is the ASP:Literal on the webpage.
                  
            if (this.DataSource != null && this.DataSource.latitudSpecified) {
                								
                // If the latitud is non-NULL, then format the value.
                // The Format method will use the Display Format
                                  string formattedValue = this.DataSource.Format(GasolineraTable.latitud);
                                
                formattedValue = HttpUtility.HtmlEncode(formattedValue);
                this.latitud.Text = formattedValue;
                   
            } 
            
            else {
            
                // latitud is NULL in the database, so use the Default Value.  
                // Default Value could also be NULL.
        
                this.latitud.Text = GasolineraTable.latitud.Format(GasolineraTable.latitud.DefaultValue);
            		
            }
            
            // If the latitud is NULL or blank, then use the value specified  
            // on Properties.
            if (this.latitud.Text == null ||
                this.latitud.Text.Trim().Length == 0) {
                // Set the value specified on the Properties.
                this.latitud.Text = "&nbsp;";
            }
                  
        }
                
        public virtual void Setlongitud()
        {
            
                    
            // Set the longitud Literal on the webpage with value from the
            // Gasolinera database record.

            // this.DataSource is the Gasolinera record retrieved from the database.
            // this.longitud is the ASP:Literal on the webpage.
                  
            if (this.DataSource != null && this.DataSource.longitudSpecified) {
                								
                // If the longitud is non-NULL, then format the value.
                // The Format method will use the Display Format
                                  string formattedValue = this.DataSource.Format(GasolineraTable.longitud);
                                
                formattedValue = HttpUtility.HtmlEncode(formattedValue);
                this.longitud.Text = formattedValue;
                   
            } 
            
            else {
            
                // longitud is NULL in the database, so use the Default Value.  
                // Default Value could also be NULL.
        
                this.longitud.Text = GasolineraTable.longitud.Format(GasolineraTable.longitud.DefaultValue);
            		
            }
            
            // If the longitud is NULL or blank, then use the value specified  
            // on Properties.
            if (this.longitud.Text == null ||
                this.longitud.Text.Trim().Length == 0) {
                // Set the value specified on the Properties.
                this.longitud.Text = "&nbsp;";
            }
                  
        }
                
        public virtual void SetNombre_Gasolinera()
        {
            
                    
            // Set the Nombre_Gasolinera Literal on the webpage with value from the
            // Gasolinera database record.

            // this.DataSource is the Gasolinera record retrieved from the database.
            // this.Nombre_Gasolinera is the ASP:Literal on the webpage.
                  
            if (this.DataSource != null && this.DataSource.Nombre_GasolineraSpecified) {
                								
                // If the Nombre_Gasolinera is non-NULL, then format the value.
                // The Format method will use the Display Format
                                  string formattedValue = this.DataSource.Format(GasolineraTable.Nombre_Gasolinera);
                                
                formattedValue = HttpUtility.HtmlEncode(formattedValue);
                this.Nombre_Gasolinera.Text = formattedValue;
                   
            } 
            
            else {
            
                // Nombre_Gasolinera is NULL in the database, so use the Default Value.  
                // Default Value could also be NULL.
        
                this.Nombre_Gasolinera.Text = GasolineraTable.Nombre_Gasolinera.Format(GasolineraTable.Nombre_Gasolinera.DefaultValue);
            		
            }
            
            // If the Nombre_Gasolinera is NULL or blank, then use the value specified  
            // on Properties.
            if (this.Nombre_Gasolinera.Text == null ||
                this.Nombre_Gasolinera.Text.Trim().Length == 0) {
                // Set the value specified on the Properties.
                this.Nombre_Gasolinera.Text = "&nbsp;";
            }
                  
        }
                
        public virtual void SetObservaciones()
        {
            
                    
            // Set the Observaciones Literal on the webpage with value from the
            // Gasolinera database record.

            // this.DataSource is the Gasolinera record retrieved from the database.
            // this.Observaciones is the ASP:Literal on the webpage.
                  
            if (this.DataSource != null && this.DataSource.ObservacionesSpecified) {
                								
                // If the Observaciones is non-NULL, then format the value.
                // The Format method will use the Display Format
                                  string formattedValue = this.DataSource.Format(GasolineraTable.Observaciones);
                                
                formattedValue = HttpUtility.HtmlEncode(formattedValue);
                this.Observaciones.Text = formattedValue;
                   
            } 
            
            else {
            
                // Observaciones is NULL in the database, so use the Default Value.  
                // Default Value could also be NULL.
        
                this.Observaciones.Text = GasolineraTable.Observaciones.Format(GasolineraTable.Observaciones.DefaultValue);
            		
            }
            
            // If the Observaciones is NULL or blank, then use the value specified  
            // on Properties.
            if (this.Observaciones.Text == null ||
                this.Observaciones.Text.Trim().Length == 0) {
                // Set the value specified on the Properties.
                this.Observaciones.Text = "&nbsp;";
            }
                  
        }
                
        public BaseClasses.Data.DataSource.EvaluateFormulaDelegate EvaluateFormulaDelegate;

        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format, System.Collections.Generic.IDictionary<string, object> variables, bool includeDS, FormulaEvaluator e)
        {
            if (e == null)
                e = new FormulaEvaluator();

            e.Variables.Clear();
            // add variables for formula evaluation
            if (variables != null)
            {
                System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, object>> enumerator = variables.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    e.Variables.Add(enumerator.Current.Key, enumerator.Current.Value);
                }
            }
            
            
            if (includeDS)
            {
                
            }
            
            // All variables referred to in the formula are expected to be
            // properties of the DataSource.  For example, referring to
            // UnitPrice as a variable will refer to DataSource.UnitPrice
            if (dataSourceForEvaluate == null)
                e.DataSource = this.DataSource;
            else
                e.DataSource = dataSourceForEvaluate;

            // Define the calling control.  This is used to add other 
            // related table and record controls as variables.
            e.CallingControl = this;

            object resultObj = e.Evaluate(formula);
            if (resultObj == null)
                return "";
            
            if ( !string.IsNullOrEmpty(format) && (string.IsNullOrEmpty(formula) || formula.IndexOf("Format(") < 0) )
                return FormulaUtils.Format(resultObj, format);
            else
                return resultObj.ToString();
        }
                
        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format, System.Collections.Generic.IDictionary<string, object> variables, bool includeDS)
        {
          return EvaluateFormula(formula, dataSourceForEvaluate, format, variables, includeDS, null);
        }

        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format, System.Collections.Generic.IDictionary<string, object> variables)
        {
          return EvaluateFormula(formula, dataSourceForEvaluate, format, variables, true, null);
        }

        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format)
        {
          return this.EvaluateFormula(formula, dataSourceForEvaluate, format, null, true, null);
        }

        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, System.Collections.Generic.IDictionary<string, object> variables, FormulaEvaluator e)
        {
          return this.EvaluateFormula(formula, dataSourceForEvaluate, null, variables, true, e);
        }

        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate)
        {
          return this.EvaluateFormula(formula, dataSourceForEvaluate, null, null, true, null);
        }

        public virtual string EvaluateFormula(string formula, bool includeDS)
        {
          return this.EvaluateFormula(formula, null, null, null, includeDS, null);
        }

        public virtual string EvaluateFormula(string formula)
        {
          return this.EvaluateFormula(formula, null, null, null, true, null);
        }
        
      

        public virtual void RegisterPostback()
        {
            
        }
    
        

        public virtual void SaveData()
        {
            // Saves the associated record in the database.
            // SaveData calls Validate and Get methods - so it may be more appropriate to
            // customize those methods.

            // 1. Load the existing record from the database. Since we save the entire record, this ensures 
            // that fields that are not displayed are also properly initialized.
            this.LoadData();
        
          
            // 2. Perform any custom validation.
            this.Validate();

            
            // 3. Set the values in the record with data from UI controls.
            // This calls the Get() method for each of the user interface controls.
            this.GetUIData();
   
            // 4. Save in the database.
            // We should not save the record if the data did not change. This
            // will save a database hit and avoid triggering any database triggers.
            
            if (this.DataSource.IsAnyValueChanged) {
                // Save record to database but do not commit yet.
                // Auto generated ids are available after saving for use by child (dependent) records.
                this.DataSource.Save();
                
                // Set the DataChanged flag to True for the for the related panels so they get refreshed as well.
                ((GasolineraTableControl)MiscUtils.GetParentControlObject(this, "GasolineraTableControl")).DataChanged = true;
                ((GasolineraTableControl)MiscUtils.GetParentControlObject(this, "GasolineraTableControl")).ResetData = true;
            }
            
      
            // update session or cookie by formula
             		  
      
            // Setting the DataChanged to True results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
            this.ResetData = true;
            
            // For Master-Detail relationships, save data on the Detail table(s)
              
        }

        public virtual void GetUIData()
        {
            // The GetUIData method retrieves the updated values from the user interface 
            // controls into a database record in preparation for saving or updating.
            // To do this, it calls the Get methods for each of the field displayed on 
            // the webpage.  It is better to make changes in the Get methods, rather 
            // than making changes here.
      
            // Call the Get methods for each of the user interface controls.
        
            GetDescripcion();
            GetGEOLocalisacion();
            Getlatitud();
            Getlongitud();
            GetNombre_Gasolinera();
            GetObservaciones();
        }
        
        
        public virtual void GetDescripcion()
        {
            
        }
                
        public virtual void GetGEOLocalisacion()
        {
            
        }
                
        public virtual void Getlatitud()
        {
            
        }
                
        public virtual void Getlongitud()
        {
            
        }
                
        public virtual void GetNombre_Gasolinera()
        {
            
        }
                
        public virtual void GetObservaciones()
        {
            
        }
                

      // To customize, override this method in GasolineraTableControlRow.
      
        public virtual WhereClause CreateWhereClause()
         
        {
        
            return null;
        
        }
        
        
    
        public virtual void Validate()
        {
            // Add custom validation for any control within this panel.
            // Example.  If you have a State ASP:Textbox control
            // if (this.State.Text != "CA")
            //    throw new Exception("State must be CA (California).");
            // The Validate method is common across all controls within
            // this panel so you can validate multiple fields, but report
            // one error message.
            
            
            
        }

        public virtual void Delete()
        {
        
            if (this.IsNewRecord) {
                return;
            }

            KeyValue pkValue = KeyValue.XmlToKey(this.RecordUniqueId);
          GasolineraTable.DeleteRecord(pkValue);
          
              
            // Setting the DataChanged to True results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            ((GasolineraTableControl)MiscUtils.GetParentControlObject(this, "GasolineraTableControl")).DataChanged = true;
            ((GasolineraTableControl)MiscUtils.GetParentControlObject(this, "GasolineraTableControl")).ResetData = true;
        }

        protected virtual void Control_PreRender(object sender, System.EventArgs e)
        {
            // PreRender event is raised just before page is being displayed.
            try {
                DbUtils.StartTransaction();
                this.RegisterPostback();
                if (!this.Page.ErrorOnPage && (this.Page.IsPageRefresh || this.DataChanged || this.ResetData)) {
                  
                
                    // Re-load the data and update the web page if necessary.
                    // This is typically done during a postback (filter, search button, sort, pagination button).
                    // In each of the other click handlers, simply set DataChanged to True to reload the data.
                    this.LoadData();
                    this.DataBind();
                }
                				
            } catch (Exception ex) {
                BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            } finally {
                DbUtils.EndTransaction();
            }
        }
        
            
        protected override void SaveControlsToSession()
        {
            base.SaveControlsToSession();
        
    
            // Save pagination state to session.
          
        }
        
        
    
        protected override void ClearControlsFromSession()
        {
            base.ClearControlsFromSession();

        

            // Clear pagination state from session.
        
        }
        
        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            string isNewRecord = (string)ViewState["IsNewRecord"];
            if (isNewRecord != null && isNewRecord.Length > 0) {
                this.IsNewRecord = Boolean.Parse(isNewRecord);
            }
        
            string myCheckSum = (string)ViewState["CheckSum"];
            if (myCheckSum != null && myCheckSum.Length > 0) {
                this.CheckSum = myCheckSum;
            }
        
    
            // Load view state for pagination control.
                 
        }

        protected override object SaveViewState()
        {
            ViewState["IsNewRecord"] = this.IsNewRecord.ToString();
            ViewState["CheckSum"] = this.CheckSum;
        

            // Load view state for pagination control.
               
            return base.SaveViewState();
        }

        
        // Event handler for ImageButton .
        public virtual void GasolineraRowCopyButton_Click(object sender, ImageClickEventArgs args)
        {
        
            // The redirect URL is set on the Properties, Custom Properties or Actions.
            // The ModifyRedirectURL call resolves the parameters before the
            // Response.Redirect redirects the page to the URL.  
            // Any code after the Response.Redirect call will not be executed, since the page is
            // redirected to the URL.
            
          string url = @"../Gasolinera/AddGasolinera.aspx?Gasolinera={PK}";
        
        bool shouldRedirect = true;
        string TargetKey = null;
        string DFKA = TargetKey;
        string id = DFKA;
        string value = id;
      
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();
                
                url = this.ModifyRedirectUrl(url, "",false);
                url = this.Page.ModifyRedirectUrl(url, "",false);
              
            } catch (Exception ex) {
                  // Upon error, rollback the transaction
                  this.Page.RollBackTransaction(sender);
                  shouldRedirect = false;
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
                DbUtils.EndTransaction();
            }
            if (shouldRedirect) {
                this.Page.ShouldSaveControlsToSession = true;
                this.Page.Response.Redirect(url);
            }
        
            else if (TargetKey != null && !shouldRedirect){
            this.Page.ShouldSaveControlsToSession = true ; 
            this.Page.CloseWindow(true);
            }
        
        }
        
        // Event handler for ImageButton .
        public virtual void GasolineraRowDeleteButton_Click(object sender, ImageClickEventArgs args)
        {
        
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();
                
            if (!this.Page.IsPageRefresh) {
        
                this.Delete();
              
            }
                this.Page.CommitTransaction(sender);
            } catch (Exception ex) {
                  // Upon error, rollback the transaction
                  this.Page.RollBackTransaction(sender);
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
                DbUtils.EndTransaction();
            }
    
        }
        
        // Event handler for ImageButton .
        public virtual void GasolineraRowEditButton_Click(object sender, ImageClickEventArgs args)
        {
        
            // The redirect URL is set on the Properties, Custom Properties or Actions.
            // The ModifyRedirectURL call resolves the parameters before the
            // Response.Redirect redirects the page to the URL.  
            // Any code after the Response.Redirect call will not be executed, since the page is
            // redirected to the URL.
            
          string url = @"../Gasolinera/EditGasolinera.aspx?Gasolinera={PK}";
        
        bool shouldRedirect = true;
        string TargetKey = null;
        string DFKA = TargetKey;
        string id = DFKA;
        string value = id;
      
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();
                
                url = this.ModifyRedirectUrl(url, "",false);
                url = this.Page.ModifyRedirectUrl(url, "",false);
              
            } catch (Exception ex) {
                  // Upon error, rollback the transaction
                  this.Page.RollBackTransaction(sender);
                  shouldRedirect = false;
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
                DbUtils.EndTransaction();
            }
            if (shouldRedirect) {
                this.Page.ShouldSaveControlsToSession = true;
                this.Page.Response.Redirect(url);
            }
        
            else if (TargetKey != null && !shouldRedirect){
            this.Page.ShouldSaveControlsToSession = true ; 
            this.Page.CloseWindow(true);
            }
        
        }
        
        // Event handler for ImageButton .
        public virtual void GasolineraRowViewButton_Click(object sender, ImageClickEventArgs args)
        {
        
            // The redirect URL is set on the Properties, Custom Properties or Actions.
            // The ModifyRedirectURL call resolves the parameters before the
            // Response.Redirect redirects the page to the URL.  
            // Any code after the Response.Redirect call will not be executed, since the page is
            // redirected to the URL.
            
          string url = @"../Gasolinera/ShowGasolinera.aspx?Gasolinera={PK}";
        
        bool shouldRedirect = true;
        string TargetKey = null;
        string DFKA = TargetKey;
        string id = DFKA;
        string value = id;
      
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();
                
                url = this.ModifyRedirectUrl(url, "",false);
                url = this.Page.ModifyRedirectUrl(url, "",false);
              
            } catch (Exception ex) {
                  // Upon error, rollback the transaction
                  this.Page.RollBackTransaction(sender);
                  shouldRedirect = false;
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
                DbUtils.EndTransaction();
            }
            if (shouldRedirect) {
                this.Page.ShouldSaveControlsToSession = true;
                this.Page.Response.Redirect(url);
            }
        
            else if (TargetKey != null && !shouldRedirect){
            this.Page.ShouldSaveControlsToSession = true ; 
            this.Page.CloseWindow(true);
            }
        
        }
        
  
        private Hashtable _PreviousUIData = new Hashtable();
        public virtual Hashtable PreviousUIData {
            get {
                return this._PreviousUIData;
            }
            set {
                this._PreviousUIData = value;
            }
        }
  
        private bool _IsNewRecord = true;
        public virtual bool IsNewRecord {
            get {
                return this._IsNewRecord;
            }
            set {
                this._IsNewRecord = value;
            }
        }

        private bool _DataChanged = false;
        public virtual bool DataChanged {
            get {
                return this._DataChanged;
            }
            set {
                this._DataChanged = value;
            }
        }

        private bool _ResetData = false;
        public virtual bool ResetData {
            get {
                return (this._ResetData);
            }
            set {
                this._ResetData = value;
            }
        }
        
        public String RecordUniqueId {
            get {
                return (string)this.ViewState["BaseGasolineraTableControlRow_Rec"];
            }
            set {
                this.ViewState["BaseGasolineraTableControlRow_Rec"] = value;
            }
        }
        
        private GasolineraRecord _DataSource;
        public GasolineraRecord DataSource {
             
            get {
                return (this._DataSource);
            }
            set {
                this._DataSource = value;
            }
        }
        
        

        private string _checkSum;
        public virtual string CheckSum {
            get {
                return (this._checkSum);
            }
            set {
                this._checkSum = value;
            }
        }
    
        private int _TotalPages;
        public virtual int TotalPages {
            get {
                return (this._TotalPages);
            }
            set {
                this._TotalPages = value;
            }
        }
        
        private int _PageIndex;
        public virtual int PageIndex {
            get {
                return (this._PageIndex);
            }
            set {
                this._PageIndex = value;
            }
        }
        
        private bool _DisplayLastPage;
        public virtual bool DisplayLastPage {
            get {
                return (this._DisplayLastPage);
            }
            set {
                this._DisplayLastPage = value;
            }
        }
        
        
    
        private KeyValue selectedParentKeyValue;
        public KeyValue SelectedParentKeyValue
        {
            get
            {
                return this.selectedParentKeyValue;
            }
            set
            {
                this.selectedParentKeyValue = value;
            }
        }
       
#region "Helper Properties"
        
        public System.Web.UI.WebControls.Literal Descripcion {
            get {
                return (System.Web.UI.WebControls.Literal)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "Descripcion");
            }
        }
            
        public System.Web.UI.WebControls.CheckBox GasolineraRecordRowSelection {
            get {
                return (System.Web.UI.WebControls.CheckBox)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraRecordRowSelection");
            }
        }
        
        public System.Web.UI.WebControls.ImageButton GasolineraRowCopyButton {
            get {
                return (System.Web.UI.WebControls.ImageButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraRowCopyButton");
            }
        }
        
        public System.Web.UI.WebControls.ImageButton GasolineraRowDeleteButton {
            get {
                return (System.Web.UI.WebControls.ImageButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraRowDeleteButton");
            }
        }
        
        public System.Web.UI.WebControls.ImageButton GasolineraRowEditButton {
            get {
                return (System.Web.UI.WebControls.ImageButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraRowEditButton");
            }
        }
        
        public System.Web.UI.WebControls.ImageButton GasolineraRowViewButton {
            get {
                return (System.Web.UI.WebControls.ImageButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraRowViewButton");
            }
        }
        
        public System.Web.UI.WebControls.Literal GEOLocalisacion {
            get {
                return (System.Web.UI.WebControls.Literal)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GEOLocalisacion");
            }
        }
            
        public System.Web.UI.WebControls.Literal latitud {
            get {
                return (System.Web.UI.WebControls.Literal)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "latitud");
            }
        }
            
        public System.Web.UI.WebControls.Literal longitud {
            get {
                return (System.Web.UI.WebControls.Literal)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "longitud");
            }
        }
            
        public System.Web.UI.WebControls.Literal Nombre_Gasolinera {
            get {
                return (System.Web.UI.WebControls.Literal)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "Nombre_Gasolinera");
            }
        }
            
        public System.Web.UI.WebControls.Literal Observaciones {
            get {
                return (System.Web.UI.WebControls.Literal)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "Observaciones");
            }
        }
            
#endregion

#region "Helper Functions"
        public override string ModifyRedirectUrl(string url, string arg, bool bEncrypt)
        {
            return this.Page.EvaluateExpressions(url, arg, bEncrypt, this);
        }

        public override string EvaluateExpressions(string url, string arg, bool bEncrypt)
        {
        GasolineraRecord rec = null;
             
            try {
                rec = this.GetRecord();
            }
            catch (Exception ) {
                // Do Nothing
            }
            
            if (rec == null && url.IndexOf("{") >= 0) {
                // Localization.
                
                throw new Exception(Page.GetResourceValue("Err:RecDataSrcNotInitialized", "EnGasAdoAPP"));
                    
            }
        
            return EvaluateExpressions(url, arg, rec, bEncrypt);
             
        }

        
        public virtual GasolineraRecord GetRecord()
             
        {
        
            if (this.DataSource != null) {
                return this.DataSource;
            }
            
            if (this.RecordUniqueId != null) {
              
                return GasolineraTable.GetRecord(this.RecordUniqueId, true);
              
            }
            
            // Localization.
            
            throw new Exception(Page.GetResourceValue("Err:RetrieveRec", "EnGasAdoAPP"));
                
        }

        public new BaseApplicationPage Page
        {
            get {
                return ((BaseApplicationPage)base.Page);
            }
        }

#endregion

}

  
// Base class for the GasolineraTableControl control on the ShowGasolineraTable page.
// Do not modify this class. Instead override any method in GasolineraTableControl.
public class BaseGasolineraTableControl : EnGasAdoAPP.UI.BaseApplicationTableControl
{
         

       public BaseGasolineraTableControl()
        {
            this.Init += Control_Init;
            this.Load += Control_Load;
            this.PreRender += Control_PreRender;
            this.EvaluateFormulaDelegate = new DataSource.EvaluateFormulaDelegate(this.EvaluateFormula);
        }

        protected virtual void Control_Init(object sender, System.EventArgs e)
        {
          
 
            // Setup the filter and search events.
        
            this.ID_marcaFilter.SelectedIndexChanged += new EventHandler(ID_marcaFilter_SelectedIndexChanged);
            this.Nombre_GasolineraFilter.SelectedIndexChanged += new EventHandler(Nombre_GasolineraFilter_SelectedIndexChanged);
            if (!this.Page.IsPostBack)
            {
                string initialVal = "";
                if  (this.InSession(this.GasolineraSearch)) 				
                    initialVal = this.GetFromSession(this.GasolineraSearch);
                
                if (initialVal != null && initialVal != "")		
                {
                        
                    this.GasolineraSearch.Text = initialVal;
                            
                    }
            }
            if (!this.Page.IsPostBack)
            {
                string initialVal = "";
                if  (this.InSession(this.ID_marcaFilter)) 				
                    initialVal = this.GetFromSession(this.ID_marcaFilter);
                
                else
                    
                    initialVal = EvaluateFormula("URL(\"ID_marca\")");
                
                if (initialVal != null && initialVal != "")		
                {
                        
                    this.ID_marcaFilter.Items.Add(new ListItem(initialVal, initialVal));
                        
                    this.ID_marcaFilter.SelectedValue = initialVal;
                            
                    }
            }
            if (!this.Page.IsPostBack)
            {
                string initialVal = "";
                if  (this.InSession(this.Nombre_GasolineraFilter)) 				
                    initialVal = this.GetFromSession(this.Nombre_GasolineraFilter);
                
                else
                    
                    initialVal = EvaluateFormula("URL(\"Nombre_Gasolinera\")");
                
                if (initialVal != null && initialVal != "")		
                {
                        
                    this.Nombre_GasolineraFilter.Items.Add(new ListItem(initialVal, initialVal));
                        
                    this.Nombre_GasolineraFilter.SelectedValue = initialVal;
                            
                    }
            }
            // Control Initializations.
            // Initialize the table's current sort order.
          
            if (this.InSession(this, "Order_By")) {
                this.CurrentSortOrder = OrderBy.FromXmlString(this.GetFromSession(this, "Order_By", null));
            } else {
                this.CurrentSortOrder = new OrderBy(true, false);
            
            }

            // Setup default pagination settings.
    
            this.PageSize = Convert.ToInt32(this.GetFromSession(this, "Page_Size", "10"));
            this.PageIndex = Convert.ToInt32(this.GetFromSession(this, "Page_Index", "0"));
            
                    
            this.ClearControlsFromSession();
        }

        protected virtual void Control_Load(object sender, EventArgs e)
        {
        
            SaveControlsToSession_Ajax();
        
              // Show confirmation message on Click
              this.GasolineraDeleteButton.Attributes.Add("onClick", "return (confirm('" + ((BaseApplicationPage)this.Page).GetResourceValue("DeleteConfirm", "EnGasAdoAPP") + "'));");
          // Setup the pagination events.
          
              this.GasolineraPagination.FirstPage.Click += new ImageClickEventHandler(GasolineraPagination_FirstPage_Click);
        
              this.GasolineraPagination.LastPage.Click += new ImageClickEventHandler(GasolineraPagination_LastPage_Click);
        
              this.GasolineraPagination.NextPage.Click += new ImageClickEventHandler(GasolineraPagination_NextPage_Click);
        
              this.GasolineraPagination.PageSizeButton.Click += GasolineraPagination_PageSizeButton_Click;
            
              this.GasolineraPagination.PreviousPage.Click += new ImageClickEventHandler(GasolineraPagination_PreviousPage_Click);
               
        
          // Setup the sorting events.
          
              this.DescripcionLabel.Click += DescripcionLabel_Click;
            
              this.GEOLocalisacionLabel.Click += GEOLocalisacionLabel_Click;
            
              this.latitudLabel.Click += latitudLabel_Click;
            
              this.longitudLabel.Click += longitudLabel_Click;
            
              this.Nombre_GasolineraLabel.Click += Nombre_GasolineraLabel_Click;
            
              this.ObservacionesLabel.Click += ObservacionesLabel_Click;
            
          // Setup the button events.
          
              this.GasolineraDeleteButton.Click += new ImageClickEventHandler(GasolineraDeleteButton_Click);
        
              this.GasolineraExportExcelButton.Click += new ImageClickEventHandler(GasolineraExportExcelButton_Click);
        							
              this.GasolineraImportButton.PostBackUrl = "../Shared/SelectFileToImport.aspx?TableName=Gasolinera"; 
              this.GasolineraImportButton.Attributes["onClick"] = "window.open('" + this.Page.EncryptUrlParameter(this.GasolineraImportButton.PostBackUrl) + "','importWindow', 'width=700, height=500,top=' +(screen.availHeight-500)/2 + ',left=' + (screen.availWidth-700)/2+ ', resizable=yes, scrollbars=yes,modal=yes'); return false;";								
                        
              this.GasolineraImportButton.Click += new ImageClickEventHandler(GasolineraImportButton_Click);
        
              this.GasolineraNewButton.Click += new ImageClickEventHandler(GasolineraNewButton_Click);
        
              this.GasolineraSearchButton.Button.Click += GasolineraSearchButton_Click;
                    
          
          // Setup events for others
            
        }

        public virtual void LoadData()
        {
          
            // Read data from database. Returns an array of records that can be assigned
            // to the DataSource table control property.
            try {
              
                  CompoundFilter joinFilter = CreateCompoundJoinFilter();
                
                  // The WHERE clause will be empty when displaying all records in table.
                  WhereClause wc = CreateWhereClause();
                  if (wc != null && !wc.RunQuery) {
                    // Initialize an empty array of records
                    ArrayList alist = new ArrayList(0);
                  Type myrec = typeof(EnGasAdoAPP.Business.GasolineraRecord);
                  this.DataSource = (GasolineraRecord[])(alist.ToArray(myrec));
                  // Add records to the list if needed.
                  this.AddNewRecords();
                  return;
                  }

                  // Call OrderBy to determine the order - either use the order defined
                  // on the Query Wizard, or specified by user (by clicking on column heading)

                  OrderBy orderBy = CreateOrderBy();
              
      
                // Get the pagesize from the pagesize control.
                this.GetPageSize();

                // Get the total number of records to be displayed.
              
                this.TotalRecords = GasolineraTable.GetRecordCount(joinFilter, wc);
              

                // Make sure PageIndex (current page) is within bounds.
                if (this.TotalPages <= 0 || this.PageIndex < 0) {
                    this.PageIndex = 0;
                }
                else if (this.DisplayLastPage || this.PageIndex >= this.TotalPages) {
                    this.PageIndex = this.TotalPages - 1;
                }

                // Retrieve the records and set the table DataSource.
                // Only PageSize records are fetched starting at PageIndex (zero based).
                if (this.TotalRecords <= 0) {
                    // No records matching query. Initialize an empty array of records
              
                    ArrayList alist = new ArrayList(0);
                    Type myrec = typeof(EnGasAdoAPP.Business.GasolineraRecord);
                    this.DataSource = (GasolineraRecord[])(alist.ToArray(myrec));
              
                }
                else if (this.AddNewRecord > 0) {
              
                    // Make sure to preserve the previously entered data on new rows.
                    ArrayList postdata = new ArrayList(0);
                    foreach (GasolineraTableControlRow rc in this.GetRecordControls()) {
                        if (!rc.IsNewRecord) {
                            rc.DataSource = rc.GetRecord();
                            rc.GetUIData();
                            postdata.Add(rc.DataSource);
                            UIData.Add(rc.PreservedUIData());
                        }
                    }
                    Type myrec = typeof(EnGasAdoAPP.Business.GasolineraRecord);
                    this.DataSource = (GasolineraRecord[])(postdata.ToArray(myrec));
              
                } 
                else {
                    // Get the records from the database
                  
                    int totalRecords = this.TotalRecords;
                    this.DataSource = GasolineraTable.GetRecords(joinFilter, wc, orderBy, this.PageIndex, this.PageSize, ref totalRecords);
                  
                }
                // Add any new rows desired by the user.
                this.AddNewRecords();
            
                // Turn off the ToggleAll checkbox
                this.GasolineraToggleAll.Checked = false;
            

                // Initialize the page and grand totals. now
            

            // Add attributes to the export csv and excel button
            
              AddWarningMessageOnClick();
            
    
            } catch (Exception ex) {
                // Report the error message to the end user
                    String msg = ex.Message;
                    if (ex.InnerException != null)
                        msg += " InnerException: " + ex.InnerException.Message;

                    throw new Exception(msg, ex.InnerException);
            }
        }
    
        
      public override void DataBind()
      {
          // The DataBind method binds the user interface controls to the values
          // from the database record for each row in the table.  To do this, it calls the
          // DataBind for each of the rows.
          // DataBind also populates any filters above the table, and sets the pagination
          // control to the correct number of records and the current page number.

          base.DataBind();

          // Make sure that the DataSource is initialized.
          if (this.DataSource == null) {
              return;
          }
          
          //  LoadData for DataSource for chart and report if they exist
               

            // Setup the pagination controls.
            BindPaginationControls();


        




    // Bind the repeater with the list of records to expand the UI.
    System.Web.UI.WebControls.Repeater rep = (System.Web.UI.WebControls.Repeater)(BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraTableControlRepeater"));
    if (rep == null){return;}
    rep.DataSource = this.DataSource;
    rep.DataBind();

    int index = 0;
    foreach (System.Web.UI.WebControls.RepeaterItem repItem in rep.Items)
    {
    // Loop through all rows in the table, set its DataSource and call DataBind().
    GasolineraTableControlRow recControl = (GasolineraTableControlRow)(repItem.FindControl("GasolineraTableControlRow"));
                recControl.DataSource = this.DataSource[index];
                if (this.UIData.Count > index) 
                    recControl.PreviousUIData = this.UIData[index];
                recControl.DataBind();
                recControl.Visible = !this.InDeletedRecordIds(recControl);
                index++;
            }
            
            // Call the Set methods for each controls on the panel
        
                SetDescripcionLabel();
                
                
                
                
                
                SetGasolineraSearch();
                
                
                
                SetGEOLocalisacionLabel();
                SetID_marcaFilter();
                SetID_marcaLabel();
                SetlatitudLabel();
                SetlongitudLabel();
                SetNombre_GasolineraFilter();
                SetNombre_GasolineraLabel();
                SetNombre_GasolineraLabel1();
                SetObservacionesLabel();
            // setting the state of expand or collapse alternative rows
      
            // Load data for each record and table UI control.
            // Ordering is important because child controls get 
            // their parent ids from their parent UI controls.
                
      
            // this method calls the set method for controls with special formula like running total, sum, rank, etc
            SetFormulaControls();
        }
        
        
        public virtual void SetFormulaControls()
        {
            // this method calls Set methods for the control that has special formula
        

    }

        
    public virtual void AddWarningMessageOnClick() {
    
        if (this.TotalRecords > 10000)
          this.GasolineraExportExcelButton.Attributes.Add("onClick", "return (confirm('" + ((BaseApplicationPage)this.Page).GetResourceValue("ExportConfirm", "EnGasAdoAPP") + "'));");
        else
          this.GasolineraExportExcelButton.Attributes.Remove("onClick");
      
    }
  

        public virtual void RegisterPostback()
        {
        
                  this.Page.RegisterPostBackTrigger(MiscUtils.FindControlRecursively(this,"GasolineraExportExcelButton"));
                                
        }
        

        
          public BaseClasses.Data.DataSource.EvaluateFormulaDelegate EvaluateFormulaDelegate;

          public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format, System.Collections.Generic.IDictionary<string, object> variables, bool includeDS, FormulaEvaluator e)
          {
            if (e == null)
                e = new FormulaEvaluator();

            e.Variables.Clear();

            // add variables for formula evaluation
            if (variables != null)
            {
                System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, object>> enumerator = variables.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    e.Variables.Add(enumerator.Current.Key, enumerator.Current.Value);
                }
            }
            if (includeDS)
            {
                
            }

            // All variables referred to in the formula are expected to be
            // properties of the DataSource.  For example, referring to
            // UnitPrice as a variable will refer to DataSource.UnitPrice
            e.DataSource = dataSourceForEvaluate;

            // Define the calling control.  This is used to add other 
            // related table and record controls as variables.
            e.CallingControl = this;

            object resultObj = e.Evaluate(formula);
            if (resultObj == null)
                return "";
            
            if ( !string.IsNullOrEmpty(format) && (string.IsNullOrEmpty(formula) || formula.IndexOf("Format(") < 0) )
                return FormulaUtils.Format(resultObj, format);
            else
                return resultObj.ToString();
        }
        
        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format, System.Collections.Generic.IDictionary<string, object> variables, bool includeDS)
        {
          return EvaluateFormula(formula, dataSourceForEvaluate, format, variables, includeDS, null);
        }

        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format, System.Collections.Generic.IDictionary<string, object> variables)
        {
          return EvaluateFormula(formula, dataSourceForEvaluate, format, variables, true, null);
        }

        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format)
        {
          return this.EvaluateFormula(formula, dataSourceForEvaluate, format, null, true, null);
        }

        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, System.Collections.Generic.IDictionary<string, object> variables, FormulaEvaluator e)
        {
          return this.EvaluateFormula(formula, dataSourceForEvaluate, null, variables, true, e);
        }

        public virtual string EvaluateFormula(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate)
        {
          return this.EvaluateFormula(formula, dataSourceForEvaluate, null, null, true, null);
        }

        public virtual string EvaluateFormula(string formula, bool includeDS)
        {
          return this.EvaluateFormula(formula, null, null, null, includeDS, null);
        }

        public virtual string EvaluateFormula(string formula)
        {
          return this.EvaluateFormula(formula, null, null, null, true, null);
        }
           
        public virtual void ResetControl()
        {
            
            this.ID_marcaFilter.ClearSelection();
            
            this.Nombre_GasolineraFilter.ClearSelection();
            
            this.GasolineraSearch.Text = "";
            
            this.CurrentSortOrder.Reset();
            if (this.InSession(this, "Order_By")) {
                this.CurrentSortOrder = OrderBy.FromXmlString(this.GetFromSession(this, "Order_By", null));
            }
            else {
                this.CurrentSortOrder = new OrderBy(true, false);
               
            }
                
            this.PageIndex = 0;
        }
        
        
        protected virtual void BindPaginationControls()
        {
            // Setup the pagination controls.

            // Bind the buttons for GasolineraTableControl pagination.
        
            this.GasolineraPagination.FirstPage.Enabled = !(this.PageIndex == 0);
            this.GasolineraPagination.LastPage.Enabled = !(this.PageIndex == this.TotalPages - 1);
            if (this.TotalPages == 0) {
                this.GasolineraPagination.LastPage.Enabled = false;
            }
          
            this.GasolineraPagination.NextPage.Enabled = !(this.PageIndex == this.TotalPages - 1);
            if (this.TotalPages == 0) {
                this.GasolineraPagination.NextPage.Enabled = false;
            }
          
            this.GasolineraPagination.PreviousPage.Enabled = !(this.PageIndex == 0);

            // Bind the pagination labels.
        
            if (this.TotalPages > 0) {
                this.GasolineraPagination.CurrentPage.Text = (this.PageIndex + 1).ToString();
            } else {
                this.GasolineraPagination.CurrentPage.Text = "0";
            }
            this.GasolineraPagination.PageSize.Text = this.PageSize.ToString();
            this.GasolineraPagination.TotalPages.Text = this.TotalPages.ToString();
        }

        public virtual void SaveData()
        {
            // Save the data from the entire table.  Calls each row's Save Data
            // to save their data.  This function is called by the Click handler of the
            // Save button.  The button handler should Start/Commit/End a transaction.
            
            foreach (GasolineraTableControlRow recCtl in this.GetRecordControls())
            {
        
                if (this.InDeletedRecordIds(recCtl)) {
                    // Delete any pending deletes. 
                    recCtl.Delete();
                }
                else {
                    if (recCtl.Visible) {
                        recCtl.SaveData();
                    }
                }
          
            }

            // Setting the DataChanged to True results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
            this.ResetData = true;
          
            // Set IsNewRecord to False for all records - since everything has been saved and is no longer "new"
            foreach (GasolineraTableControlRow recCtl in this.GetRecordControls()){
                recCtl.IsNewRecord = false;
            }
      
            // Set DeletedRecordsIds to Nothing since we have deleted all pending deletes.
            this.DeletedRecordIds = null;
      
        }
        
        public virtual CompoundFilter CreateCompoundJoinFilter()
        {
            CompoundFilter jFilter = new CompoundFilter();
        
            return jFilter;
        }      
        
    
        public virtual OrderBy CreateOrderBy()
        {
            // The CurrentSortOrder is initialized to the sort order on the 
            // Query Wizard.  It may be modified by the Click handler for any of
            // the column heading to sort or reverse sort by that column.
            // You can add your own sort order, or modify it on the Query Wizard.
            return this.CurrentSortOrder;
        }
         
        
        private string parentSelectedKeyValue;
        public string ParentSelectedKeyValue
        {
          get
          {
            return parentSelectedKeyValue;
          }
          set
          {
            parentSelectedKeyValue = value;
          }
        }

    
        public virtual WhereClause CreateWhereClause()
        {
            // This CreateWhereClause is used for loading the data.
            GasolineraTable.Instance.InnerFilter = null;
            WhereClause wc = new WhereClause();
         
            // CreateWhereClause() Compose the WHERE clause consiting of:
            // 1. Static clause defined at design time.
            // 2. User selected search criteria.
            // 3. User selected filter criteria.
            
        
            if (MiscUtils.IsValueSelected(this.GasolineraSearch)) {
                // Strip "..." from begin and ending of the search text, otherwise the search will return 0 values as in database "..." is not stored.
                if (this.GasolineraSearch.Text.StartsWith("...")) {
                    this.GasolineraSearch.Text = this.GasolineraSearch.Text.Substring(3,this.GasolineraSearch.Text.Length-3);
                }
                if (this.GasolineraSearch.Text.EndsWith("...")) {
                    this.GasolineraSearch.Text = this.GasolineraSearch.Text.Substring(0,this.GasolineraSearch.Text.Length-3);
                    // Strip the last word as well as it is likely only a partial word
                    int endindex = this.GasolineraSearch.Text.Length - 1;
                    while (!Char.IsWhiteSpace(GasolineraSearch.Text[endindex]) && endindex > 0) {
                        endindex--;
                    }
                    if (endindex > 0) {
                        this.GasolineraSearch.Text = this.GasolineraSearch.Text.Substring(0, endindex);
                    }
                }
                string formatedSearchText = MiscUtils.GetSelectedValue(this.GasolineraSearch, this.GetFromSession(this.GasolineraSearch));
                // After stripping "..." see if the search text is null or empty.
                if (MiscUtils.IsValueSelected(this.GasolineraSearch)) {
                      
                    // These clauses are added depending on operator and fields selected in Control's property page, bindings tab.
                  
                    WhereClause search = new WhereClause();
                    
                    search.iOR(GasolineraTable.Nombre_Gasolinera, BaseFilter.ComparisonOperator.Contains, formatedSearchText, true, false);
        
                    search.iOR(GasolineraTable.GEOLocalisacion, BaseFilter.ComparisonOperator.Contains, formatedSearchText, true, false);
        
                    wc.iAND(search);
                  
                }
            }
                  
            if (MiscUtils.IsValueSelected(this.ID_marcaFilter)) {
                        
                wc.iAND(GasolineraTable.ID_marca, BaseFilter.ComparisonOperator.EqualsTo, MiscUtils.GetSelectedValue(this.ID_marcaFilter, this.GetFromSession(this.ID_marcaFilter)), false, false);
            
            }
                      
            if (MiscUtils.IsValueSelected(this.Nombre_GasolineraFilter)) {
                        
                wc.iAND(GasolineraTable.Nombre_Gasolinera, BaseFilter.ComparisonOperator.EqualsTo, MiscUtils.GetSelectedValue(this.Nombre_GasolineraFilter, this.GetFromSession(this.Nombre_GasolineraFilter)), false, false);
            
            }
                      
            return wc;
        }
        
         
        public virtual WhereClause CreateWhereClause(String searchText, String fromSearchControl, String AutoTypeAheadSearch, String AutoTypeAheadWordSeparators)
        {
            // This CreateWhereClause is used for loading list of suggestions for Auto Type-Ahead feature.
            GasolineraTable.Instance.InnerFilter = null;
            WhereClause wc = new WhereClause();
        
            // Compose the WHERE clause consiting of:
            // 1. Static clause defined at design time.
            // 2. User selected search criteria.
            // 3. User selected filter criteria.
            
            String appRelativeVirtualPath = (String)HttpContext.Current.Session["AppRelativeVirtualPath"];
            
            // Adds clauses if values are selected in Filter controls which are configured in the page.
          
            if (MiscUtils.IsValueSelected(searchText) && fromSearchControl == "GasolineraSearch") {
                String formatedSearchText = searchText;
                // strip "..." from begin and ending of the search text, otherwise the search will return 0 values as in database "..." is not stored.
                
                  if (searchText.StartsWith("...")) {
                      formatedSearchText = searchText.Substring(3,searchText.Length-3);
                  }
                  if (searchText.EndsWith("...")) {
                      formatedSearchText = searchText.Substring(0,searchText.Length-3);
                  }
                
                // After stripping "...", trim any leading and trailing whitespaces 
                formatedSearchText = formatedSearchText.Trim();
                // After stripping "..." see if the search text is null or empty.
                if (MiscUtils.IsValueSelected(searchText)) {
                      
                    // These clauses are added depending on operator and fields selected in Control's property page, bindings tab.
                  
                    WhereClause search = new WhereClause();
                    
                    if (StringUtils.InvariantLCase(AutoTypeAheadSearch).Equals("wordsstartingwithsearchstring")) {
                
                        search.iOR(GasolineraTable.Nombre_Gasolinera, BaseFilter.ComparisonOperator.Starts_With, formatedSearchText, true, false);
                        search.iOR(GasolineraTable.Nombre_Gasolinera, BaseFilter.ComparisonOperator.Contains, AutoTypeAheadWordSeparators + formatedSearchText, true, false);
                  
                
                        search.iOR(GasolineraTable.GEOLocalisacion, BaseFilter.ComparisonOperator.Starts_With, formatedSearchText, true, false);
                        search.iOR(GasolineraTable.GEOLocalisacion, BaseFilter.ComparisonOperator.Contains, AutoTypeAheadWordSeparators + formatedSearchText, true, false);
                  
                
                    } else {
                        
                        search.iOR(GasolineraTable.Nombre_Gasolinera, BaseFilter.ComparisonOperator.Contains, formatedSearchText, true, false);
                        search.iOR(GasolineraTable.GEOLocalisacion, BaseFilter.ComparisonOperator.Contains, formatedSearchText, true, false);
                    } 
                    wc.iAND(search);
                  
                }
            }
                  
      String ID_marcaFilterSelectedValue = (String)HttpContext.Current.Session[HttpContext.Current.Session.SessionID + appRelativeVirtualPath + "ID_marcaFilter_Ajax"];
            if (MiscUtils.IsValueSelected(ID_marcaFilterSelectedValue)) {
              
                wc.iAND(GasolineraTable.ID_marca, BaseFilter.ComparisonOperator.EqualsTo, ID_marcaFilterSelectedValue, false, false);
                    
      }
                      
      String Nombre_GasolineraFilterSelectedValue = (String)HttpContext.Current.Session[HttpContext.Current.Session.SessionID + appRelativeVirtualPath + "Nombre_GasolineraFilter_Ajax"];
            if (MiscUtils.IsValueSelected(Nombre_GasolineraFilterSelectedValue)) {
              
                wc.iAND(GasolineraTable.Nombre_Gasolinera, BaseFilter.ComparisonOperator.EqualsTo, Nombre_GasolineraFilterSelectedValue, false, false);
                    
      }
                      
            return wc;
        }
          
        public virtual string[] GetAutoCompletionList_GasolineraSearch(String prefixText,int count)
        {
            ArrayList resultList = new ArrayList();
            ArrayList wordList= new ArrayList();
            int iteration = 0;
            
            WhereClause wc = CreateWhereClause(prefixText,"GasolineraSearch", "WordsStartingWithSearchString", "[^a-zA-Z0-9]");
            while (resultList.Count < count && iteration < 5){
                // Fetch 100 records in each iteration
                EnGasAdoAPP.Business.GasolineraRecord[] recordList  = GasolineraTable.GetRecords(wc, null, iteration, 100);
                String resultItem = "";
                foreach (GasolineraRecord rec in recordList ){
                    // Exit the loop if recordList count has reached AutoTypeAheadListSize.
                    if (resultList.Count >= count) {
                        break;
                    }
                    // If the field is configured to Display as Foreign key, Format() method returns the 
                    // Display as Forien Key value instead of original field value.
                    // Since search had to be done in multiple fields (selected in Control's page property, binding tab) in a record,
                    // We need to find relevent field to display which matches the prefixText and is not already present in the result list.
            
                    resultItem = rec.Format(GasolineraTable.Nombre_Gasolinera);
      
                    if (resultItem != null && resultItem.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture).Contains(prefixText.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture))) {
                        bool isAdded = FormatSuggestions(prefixText, resultItem, 50, "AtBeginningOfMatchedString", "WordsStartingWithSearchString", "[^a-zA-Z0-9]", resultList);
                        if (isAdded) {
                            continue;
                        }
                    }
      
                    resultItem = rec.Format(GasolineraTable.GEOLocalisacion);
      
                    if (resultItem != null && resultItem.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture).Contains(prefixText.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture))) {
                        bool isAdded = FormatSuggestions(prefixText, resultItem, 50, "AtBeginningOfMatchedString", "WordsStartingWithSearchString", "[^a-zA-Z0-9]", resultList);
                        if (isAdded) {
                            continue;
                        }
                    }
      
                }
                // Exit the loop if number of records found is less as further iteration will not return any more records
                if (recordList .Length < 100 ) {
                    break;
                }
                iteration++;
            }
              
            resultList.Sort();
            string[] result = new string[resultList.Count];
            Array.Copy(resultList.ToArray(), result, resultList.Count);
            return result;
        }
          
        public virtual bool FormatSuggestions(String prefixText, String resultItem,
                                              int columnLength, String AutoTypeAheadDisplayFoundText,
                                              String autoTypeAheadSearch, String AutoTypeAheadWordSeparators,
                                              ArrayList resultList)
        {
            // Formats the result Item and adds it to the list of suggestions.
            int index  = resultItem.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture).IndexOf(prefixText.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture));
            String itemToAdd = null;
            bool isFound = false;
            bool isAdded = false;
            if (StringUtils.InvariantLCase(autoTypeAheadSearch).Equals("wordsstartingwithsearchstring") && !(index == 0)) {
                 // Expression to find word which contains AutoTypeAheadWordSeparators followed by prefixText
                System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex( AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (regex1.IsMatch(resultItem)) {
                    index = regex1.Match(resultItem).Index;
                    isFound = true;
                }
                //If the prefixText is found immediatly after white space then starting of the word is found so don not search any further
                if (resultItem[index].ToString() != " ") {
                    // Expression to find beginning of the word which contains AutoTypeAheadWordSeparators followed by prefixText
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\\S*" + AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    if (regex.IsMatch(resultItem)) {
                        index = regex.Match(resultItem).Index;
                        isFound = true;
                    }
                }
            }
            // If autoTypeAheadSearch value is wordsstartingwithsearchstring then, extract the substring only if the prefixText is found at the 
            // beginning of the resultItem (index = 0) or a word in resultItem is found starts with prefixText. 
            if (index == 0 || isFound || StringUtils.InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring")) {
                if (StringUtils.InvariantLCase(AutoTypeAheadDisplayFoundText).Equals("atbeginningofmatchedstring")) {
                    // Expression to find beginning of the word which contains prefixText
                    System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex("\\S*" + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    //  Find the beginning of the word which contains prefexText
                    if (StringUtils.InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring") && regex1.IsMatch(resultItem)) {
                        index = regex1.Match(resultItem).Index;
                        isFound = true;
                    }
                    // Display string from the index till end of the string if, sub string from index till end of string is less than columnLength value.
                    if ((resultItem.Length - index) <= columnLength) {
                        if (index == 0) {
                            itemToAdd = resultItem;
                        } else {
                            itemToAdd = "..." + resultItem.Substring(index, resultItem.Length - index);
                        }
                    } else {
                        if (index == 0) {
                          itemToAdd = resultItem.Substring(index, (columnLength - 3)) + "...";
                        } else {
                            // Truncate the string to show only columnLength - 6 characters as begining and trailing "..." has to be appended.
                            itemToAdd = "..." + resultItem.Substring(index, (columnLength - 6)) + "...";
                        }
                    }
                } else if (StringUtils.InvariantLCase(AutoTypeAheadDisplayFoundText).Equals("inmiddleofmatchedstring")) {
                    int subStringBeginIndex = (int)(columnLength / 2);
                    if (resultItem.Length <= columnLength) {
                        itemToAdd = resultItem;
                    } else {
                        // Sanity check at end of the string
                        if ((index + prefixText.Length) == columnLength) {
                            itemToAdd = "..." + resultItem.Substring((index - columnLength), index);
                        } else if ((resultItem.Length - index) < subStringBeginIndex) {
                            //  Display string from the end till columnLength value if, index is closer to the end of the string.
                            itemToAdd = "..." + resultItem.Substring(resultItem.Length - columnLength, resultItem.Length);
                        } else if (index <= subStringBeginIndex) {
                            // Sanity chet at beginning of the string
                            itemToAdd = resultItem.Substring(0, columnLength) + "...";
                        } else {
                            // Display string containing text before the prefixText occures and text after the prefixText
                            itemToAdd = "..." + resultItem.Substring(index - subStringBeginIndex, columnLength) + "...";
                        }
                    }
                } else if (StringUtils.InvariantLCase(AutoTypeAheadDisplayFoundText).Equals("atendofmatchedstring")) {
                     // Expression to find ending of the word which contains prefexText
                    System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex("\\s", System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
                    // Find the ending of the word which contains prefexText
                    if (regex1.IsMatch(resultItem, index + 1)) {
                        index = regex1.Match(resultItem, index + 1).Index;
                    }else{
                        // If the word which contains prefexText is the last word in string, regex1.IsMatch returns false.
                        index = resultItem.Length;
                    }
                    
                    if (index > resultItem.Length) {
                        index = resultItem.Length;
                    }
                    // If text from beginning of the string till index is less than columnLength value then, display string from the beginning till index.
                    if (index <= columnLength) {
                        if (index == resultItem.Length) {   //Make decision to append "..."
                            itemToAdd = resultItem.Substring(0, index);
                        } else {
                            itemToAdd = resultItem.Substring(0, index) + "...";
                        }
                    } else if (index == resultItem.Length) {
                        itemToAdd = "..." + resultItem.Substring(index - (columnLength - 3), columnLength - 3);
                    } else {
                        // Truncate the string to show only columnLength - 6 characters as begining and trailing "..." has to be appended.
                        itemToAdd = "..." + resultItem.Substring(index - (columnLength - 6), (columnLength - 6)) + "...";
                    }
                }
                
                // Remove newline character from itemToAdd
                int prefixTextIndex = itemToAdd.IndexOf(prefixText, StringComparison.CurrentCultureIgnoreCase);
                // If itemToAdd contains any newline after the search text then show text only till newline
                System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex("(\r\n|\n)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                int newLineIndexAfterPrefix = -1;
                if (regex2.IsMatch(itemToAdd, prefixTextIndex)){
                    newLineIndexAfterPrefix = regex2.Match(itemToAdd, prefixTextIndex).Index;
                }
                if ((newLineIndexAfterPrefix > -1)) {
                    if (itemToAdd.EndsWith("...")) {
                        itemToAdd = itemToAdd.Substring(0, newLineIndexAfterPrefix) + "...";
                    }
                    else {
                        itemToAdd = itemToAdd.Substring(0, newLineIndexAfterPrefix);
                    }
                }
                // If itemToAdd contains any newline before search text then show text which comes after newline
                System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex("(\r\n|\n)", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.RightToLeft );
                int newLineIndexBeforePrefix = -1;
                if (regex3.IsMatch(itemToAdd, prefixTextIndex)){
                    newLineIndexBeforePrefix = regex3.Match(itemToAdd, prefixTextIndex).Index;
                }
                if ((newLineIndexBeforePrefix > -1)) {
                    if (itemToAdd.StartsWith("...")) {
                        itemToAdd = "..." + itemToAdd.Substring(newLineIndexBeforePrefix +regex3.Match(itemToAdd, prefixTextIndex).Length);
                    }
                    else {
                        itemToAdd = itemToAdd.Substring(newLineIndexBeforePrefix +regex3.Match(itemToAdd, prefixTextIndex).Length);
                    }
                }

                if (itemToAdd!= null && !resultList.Contains(itemToAdd)) {
                    
                    resultList.Add(itemToAdd);
          								
                    isAdded = true;
                }
            }
            return isAdded;
        }
        
        
    
        protected virtual void GetPageSize()
        {
        
            if (this.GasolineraPagination.PageSize.Text.Length > 0) {
                try {
                    // this.PageSize = Convert.ToInt32(this.GasolineraPagination.PageSize.Text);
                } catch (Exception ) {
                }
            }
        }

        protected virtual void AddNewRecords()
        {
          
            ArrayList newRecordList = new ArrayList();
          
            System.Collections.Generic.List<Hashtable> newUIDataList = new System.Collections.Generic.List<Hashtable>();
    // Loop though all the record controls and if the record control
    // does not have a unique record id set, then create a record
    // and add to the list.
    if (!this.ResetData)
    {
    System.Web.UI.WebControls.Repeater rep = (System.Web.UI.WebControls.Repeater)(BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraTableControlRepeater"));
    if (rep == null){return;}

    foreach (System.Web.UI.WebControls.RepeaterItem repItem in rep.Items)
    {
    // Loop through all rows in the table, set its DataSource and call DataBind().
    GasolineraTableControlRow recControl = (GasolineraTableControlRow)(repItem.FindControl("GasolineraTableControlRow"));

                    if (recControl.Visible && recControl.IsNewRecord) {
                      GasolineraRecord rec = new GasolineraRecord();
        
                        if (recControl.Descripcion.Text != "") {
                            rec.Parse(recControl.Descripcion.Text, GasolineraTable.Descripcion);
                  }
                
                        if (recControl.GEOLocalisacion.Text != "") {
                            rec.Parse(recControl.GEOLocalisacion.Text, GasolineraTable.GEOLocalisacion);
                  }
                
                        if (recControl.latitud.Text != "") {
                            rec.Parse(recControl.latitud.Text, GasolineraTable.latitud);
                  }
                
                        if (recControl.longitud.Text != "") {
                            rec.Parse(recControl.longitud.Text, GasolineraTable.longitud);
                  }
                
                        if (recControl.Nombre_Gasolinera.Text != "") {
                            rec.Parse(recControl.Nombre_Gasolinera.Text, GasolineraTable.Nombre_Gasolinera);
                  }
                
                        if (recControl.Observaciones.Text != "") {
                            rec.Parse(recControl.Observaciones.Text, GasolineraTable.Observaciones);
                  }
                
                        newUIDataList.Add(recControl.PreservedUIData());
                        newRecordList.Add(rec);
                    }
                }
            }

            // Add any new record to the list.
            for (int count = 1; count <= this.AddNewRecord; count++) {
              
                newRecordList.Insert(0, new GasolineraRecord());
                newUIDataList.Insert(0, new Hashtable());
              
            }
            this.AddNewRecord = 0;

            // Finally, add any new records to the DataSource.
            if (newRecordList.Count > 0) {
              
                ArrayList finalList = new ArrayList(this.DataSource);
                finalList.InsertRange(0, newRecordList);

                Type myrec = typeof(EnGasAdoAPP.Business.GasolineraRecord);
                this.DataSource = (GasolineraRecord[])(finalList.ToArray(myrec));
              
            }
            
            // Add the existing UI data to this hash table
            if (newUIDataList.Count > 0)
                this.UIData.InsertRange(0, newUIDataList);
        }

        
        public void AddToDeletedRecordIds(GasolineraTableControlRow rec)
        {
            if (rec.IsNewRecord) {
                return;
            }

            if (this.DeletedRecordIds != null && this.DeletedRecordIds.Length > 0) {
                this.DeletedRecordIds += ",";
            }

            this.DeletedRecordIds += "[" + rec.RecordUniqueId + "]";
        }

        protected virtual bool InDeletedRecordIds(GasolineraTableControlRow rec)            
        {
            if (this.DeletedRecordIds == null || this.DeletedRecordIds.Length == 0) {
                return (false);
            }

            return (this.DeletedRecordIds.IndexOf("[" + rec.RecordUniqueId + "]") >= 0);
        }

        private String _DeletedRecordIds;
        public String DeletedRecordIds {
            get {
                return (this._DeletedRecordIds);
            }
            set {
                this._DeletedRecordIds = value;
            }
        }
        
      
        // Create Set, WhereClause, and Populate Methods
        
        public virtual void SetDescripcionLabel()
                  {
                  
                    
        }
                
        public virtual void SetGEOLocalisacionLabel()
                  {
                  
                    
        }
                
        public virtual void SetID_marcaLabel()
                  {
                  
                    
        }
                
        public virtual void SetlatitudLabel()
                  {
                  
                    
        }
                
        public virtual void SetlongitudLabel()
                  {
                  
                    
        }
                
        public virtual void SetNombre_GasolineraLabel()
                  {
                  
                    
        }
                
        public virtual void SetNombre_GasolineraLabel1()
                  {
                  
                    
        }
                
        public virtual void SetObservacionesLabel()
                  {
                  
                    
        }
                
        public virtual void SetGasolineraSearch()
        {
            
        }
            
        public virtual void SetID_marcaFilter()
        {
            
                this.PopulateID_marcaFilter(MiscUtils.GetSelectedValue(this.ID_marcaFilter,  GetFromSession(this.ID_marcaFilter)), 500);					
                    
        }
            
        public virtual void SetNombre_GasolineraFilter()
        {
            
                this.PopulateNombre_GasolineraFilter(MiscUtils.GetSelectedValue(this.Nombre_GasolineraFilter,  GetFromSession(this.Nombre_GasolineraFilter)), 500);					
                    
        }
            
        // Get the filters' data for ID_marcaFilter.
                
        protected virtual void PopulateID_marcaFilter(string selectedValue, int maxItems)
                    
        {
            this.ID_marcaFilter.Items.Clear();
                        
            		  			
            // Set up the WHERE and the ORDER BY clause by calling the CreateWhereClause_ID_marcaFilter function.
            // It is better to customize the where clause there.
          						
            //Setup the WHERE clause.
            WhereClause wc =this.CreateWhereClause_ID_marcaFilter();		
            
            // Setup the static list items        
            
            // Add the All item.
            this.ID_marcaFilter.Items.Insert(0, new ListItem(this.Page.GetResourceValue("Txt:All", "EnGasAdoAPP"), "--ANY--"));
                            
            OrderBy orderBy = new OrderBy(false, false);
                          orderBy.Add(Marca_gasolineraTable.Descripcion, OrderByItem.OrderDir.Asc);


            System.Collections.Generic.IDictionary<string, object> variables = new System.Collections.Generic.Dictionary<string, object> ();

            

            string noValueFormat = Page.GetResourceValue("Txt:Other", "EnGasAdoAPP");

            Marca_gasolineraRecord[] itemValues  = null;
            if (wc.RunQuery)
            {
                int counter = 0;
                int pageNum = 0;
                FormulaEvaluator evaluator = new FormulaEvaluator();
                
                
                do
                {
                    
                    itemValues = Marca_gasolineraTable.GetRecords(wc, orderBy, pageNum, maxItems);
                                    
                    foreach (Marca_gasolineraRecord itemValue in itemValues) 
                    {
                        // Create the item and add to the list.
                        string cvalue = null;
                        string fvalue = null;
                        if (itemValue.ID_MarcaSpecified) 
                        {
                            cvalue = itemValue.ID_Marca.ToString();
                            if (counter < maxItems && this.ID_marcaFilter.Items.FindByValue(cvalue) == null)
                            {
                                    
                                Boolean _isExpandableNonCompositeForeignKey = GasolineraTable.Instance.TableDefinition.IsExpandableNonCompositeForeignKey(GasolineraTable.ID_marca);
                                if(_isExpandableNonCompositeForeignKey && GasolineraTable.ID_marca.IsApplyDisplayAs)
                                     fvalue = GasolineraTable.GetDFKA(itemValue, GasolineraTable.ID_marca);
                                if ((!_isExpandableNonCompositeForeignKey) || (String.IsNullOrEmpty(fvalue)))
                                     fvalue = itemValue.Format(Marca_gasolineraTable.Descripcion);
                                   					
                                if (fvalue == null || fvalue.Trim() == "") fvalue = cvalue;
                                ListItem newItem = new ListItem(fvalue, cvalue);
                                this.ID_marcaFilter.Items.Add(newItem);
                                counter += 1;
                            }
                        }
                    }
                    pageNum++;
                }
                while (itemValues.Length == maxItems && counter < maxItems);
            }
        
          
      
            // Set the selected value.
            MiscUtils.SetSelectedValue(this.ID_marcaFilter, selectedValue);

            
        }
            
        // Get the filters' data for Nombre_GasolineraFilter.
                
        protected virtual void PopulateNombre_GasolineraFilter(string selectedValue, int maxItems)
                    
        {
            this.Nombre_GasolineraFilter.Items.Clear();
                        
            		  			
            // Set up the WHERE and the ORDER BY clause by calling the CreateWhereClause_Nombre_GasolineraFilter function.
            // It is better to customize the where clause there.
          
            // Setup the WHERE clause, 
                
            WhereClause wc = this.CreateWhereClause_Nombre_GasolineraFilter();

            // Setup the static list items        
            
            // Add the All item.
            this.Nombre_GasolineraFilter.Items.Insert(0, new ListItem(this.Page.GetResourceValue("Txt:All", "EnGasAdoAPP"), "--ANY--"));
                            

            OrderBy orderBy = new OrderBy(false, false);
            orderBy.Add(GasolineraTable.Nombre_Gasolinera, OrderByItem.OrderDir.Asc);                

            
            string[] values = GasolineraTable.GetValues(GasolineraTable.Nombre_Gasolinera, wc, orderBy, maxItems);              
            
            foreach (string itemValue in values)
            {
            // Create the item and add to the list.
            string fvalue;
            if ( GasolineraTable.Nombre_Gasolinera.IsColumnValueTypeBoolean()) {
                    fvalue = itemValue;
                }else {
                    fvalue = GasolineraTable.Nombre_Gasolinera.Format(itemValue);
                }
                ListItem item = new ListItem(fvalue, itemValue);
                this.Nombre_GasolineraFilter.Items.Add(item);
            }
          
      
            // Set the selected value.
            MiscUtils.SetSelectedValue(this.Nombre_GasolineraFilter, selectedValue);

            
        }
            
        public virtual WhereClause CreateWhereClause_ID_marcaFilter()
        {
        
            // Create a where clause for the filter ID_marcaFilter.
            // This function is called by the Populate method to load the items 
            // in the ID_marcaFilterDropDownList
        
            WhereClause wc = new WhereClause();
            return wc;
            
        }
      
        public virtual WhereClause CreateWhereClause_Nombre_GasolineraFilter()
        {
        
            // Create a where clause for the filter Nombre_GasolineraFilter.
            // This function is called by the Populate method to load the items 
            // in the Nombre_GasolineraFilterDropDownList
        
            WhereClause wc = new WhereClause();
            return wc;
            
        }
      

    
        protected virtual void Control_PreRender(object sender, System.EventArgs e)
        {
            // PreRender event is raised just before page is being displayed.
            try {
                DbUtils.StartTransaction();
                this.RegisterPostback();
                if (!this.Page.ErrorOnPage && (this.Page.IsPageRefresh || this.DataChanged || this.ResetData)) {
                  
                
                    // Re-load the data and update the web page if necessary.
                    // This is typically done during a postback (filter, search button, sort, pagination button).
                    // In each of the other click handlers, simply set DataChanged to True to reload the data.
                    
                    this.LoadData();
                    this.DataBind();					
                    
                }
                                
            } catch (Exception ex) {
                BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            } finally {
                DbUtils.EndTransaction();
            }
        }
        
        
        protected override void SaveControlsToSession()
        {
            base.SaveControlsToSession();
            // Save filter controls to values to session.
        
            this.SaveToSession(this.GasolineraSearch, this.GasolineraSearch.Text);
                  
            this.SaveToSession(this.ID_marcaFilter, this.ID_marcaFilter.SelectedValue);
                  
            this.SaveToSession(this.Nombre_GasolineraFilter, this.Nombre_GasolineraFilter.SelectedValue);
                  
            
                    
            // Save pagination state to session.
        
    
            // Save table control properties to the session.
          
            if (this.CurrentSortOrder != null) {
                this.SaveToSession(this, "Order_By", this.CurrentSortOrder.ToXmlString());
            }
          
            this.SaveToSession(this, "Page_Index", this.PageIndex.ToString());
            this.SaveToSession(this, "Page_Size", this.PageSize.ToString());
        
            this.SaveToSession(this, "DeletedRecordIds", this.DeletedRecordIds);
        
        }
        
        
        protected  void SaveControlsToSession_Ajax()
        {
            // Save filter controls to values to session.
          
      this.SaveToSession("GasolineraSearch_Ajax", this.GasolineraSearch.Text);
              
      this.SaveToSession("ID_marcaFilter_Ajax", this.ID_marcaFilter.SelectedValue);
              
      this.SaveToSession("Nombre_GasolineraFilter_Ajax", this.Nombre_GasolineraFilter.SelectedValue);
              
           HttpContext.Current.Session["AppRelativeVirtualPath"] = this.Page.AppRelativeVirtualPath;
         
        }
        
        
        protected override void ClearControlsFromSession()
        {
            base.ClearControlsFromSession();
            // Clear filter controls values from the session.
        
            this.RemoveFromSession(this.GasolineraSearch);
            this.RemoveFromSession(this.ID_marcaFilter);
            this.RemoveFromSession(this.Nombre_GasolineraFilter);
            
            // Clear pagination state from session.
        
    
            // Clear table properties from the session.
            this.RemoveFromSession(this, "Order_By");
            this.RemoveFromSession(this, "Page_Index");
            this.RemoveFromSession(this, "Page_Size");
            
            this.RemoveFromSession(this, "DeletedRecordIds");
            
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);

            string orderByStr = (string)ViewState["GasolineraTableControl_OrderBy"];
          
            if (orderByStr != null && orderByStr.Length > 0) {
                this.CurrentSortOrder = BaseClasses.Data.OrderBy.FromXmlString(orderByStr);
            }
            else {
                this.CurrentSortOrder = new OrderBy(true, false);
            }
          

            if (ViewState["Page_Index"] != null) {
                this.PageIndex = (int)ViewState["Page_Index"];
            }

            if (ViewState["Page_Size"] != null) {
                this.PageSize = (int)ViewState["Page_Size"];
            }
            
            // Load view state for pagination control.
        
            this.DeletedRecordIds = (string)this.ViewState["DeletedRecordIds"];
        
        }

        protected override object SaveViewState()
        {            
          
            if (this.CurrentSortOrder != null) {
                this.ViewState["GasolineraTableControl_OrderBy"] = this.CurrentSortOrder.ToXmlString();
            }
          
            
            this.ViewState["Page_Index"] = this.PageIndex;
            this.ViewState["Page_Size"] = this.PageSize;
        
            this.ViewState["DeletedRecordIds"] = this.DeletedRecordIds;
        
    
            // Load view state for pagination control.
              
            return (base.SaveViewState());
        }
        
        // Generate the event handling functions for pagination events.
        
        // Event handler for GasolineraPaginationImageButton .
        public virtual void GasolineraPagination_FirstPage_Click(object sender, ImageClickEventArgs args)
        {
        
            try {
                
            this.PageIndex = 0;
            this.DataChanged = true;
      
            } catch (Exception ex) {
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
    
            }
    
        }
        
        // Event handler for GasolineraPaginationImageButton .
        public virtual void GasolineraPagination_LastPage_Click(object sender, ImageClickEventArgs args)
        {
        
            try {
                
            this.DisplayLastPage = true;
            this.DataChanged = true;
      
            } catch (Exception ex) {
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
    
            }
    
        }
        
        // Event handler for GasolineraPaginationImageButton .
        public virtual void GasolineraPagination_NextPage_Click(object sender, ImageClickEventArgs args)
        {
        
            try {
                
            this.PageIndex += 1;
            this.DataChanged = true;
      
            } catch (Exception ex) {
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
    
            }
    
        }
        
        // event handler for GasolineraPaginationPageSizeButtonLinkButton  
        public virtual void GasolineraPagination_PageSizeButton_Click(object sender, EventArgs args)
        {
        
            try {
                
            this.DataChanged = true;
      
            this.PageSize = Convert.ToInt32(this.GasolineraPagination.PageSize.Text);
      
            this.PageIndex = Convert.ToInt32(this.GasolineraPagination.CurrentPage.Text) - 1;
      
            } catch (Exception ex) {
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
    
            }
    
        }
        
        // Event handler for GasolineraPaginationImageButton .
        public virtual void GasolineraPagination_PreviousPage_Click(object sender, ImageClickEventArgs args)
        {
        
            try {
                
            if (this.PageIndex > 0) {
                this.PageIndex -= 1;
                this.DataChanged = true;
            }
      
            } catch (Exception ex) {
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
    
            }
    
        }
        

        // Generate the event handling functions for sorting events.
        
        public virtual void DescripcionLabel_Click(object sender, EventArgs args)
        {
            //Sorts by Descripcion when clicked.
              
            // Get previous sorting state for Descripcion.
        
            OrderByItem sd = this.CurrentSortOrder.Find(GasolineraTable.Descripcion);
            if (sd == null || (this.CurrentSortOrder.Items != null && this.CurrentSortOrder.Items.Length > 1)) {
                // First time sort, so add sort order for Descripcion.
                this.CurrentSortOrder.Reset();
                this.CurrentSortOrder.Add(GasolineraTable.Descripcion, OrderByItem.OrderDir.Asc);
            } else {
                // Previously sorted by Descripcion, so just reverse.
                sd.Reverse();
            }
        

            // Setting the DataChanged to true results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
              
        }
            
        public virtual void GEOLocalisacionLabel_Click(object sender, EventArgs args)
        {
            //Sorts by GEOLocalisacion when clicked.
              
            // Get previous sorting state for GEOLocalisacion.
        
            OrderByItem sd = this.CurrentSortOrder.Find(GasolineraTable.GEOLocalisacion);
            if (sd == null || (this.CurrentSortOrder.Items != null && this.CurrentSortOrder.Items.Length > 1)) {
                // First time sort, so add sort order for GEOLocalisacion.
                this.CurrentSortOrder.Reset();
                this.CurrentSortOrder.Add(GasolineraTable.GEOLocalisacion, OrderByItem.OrderDir.Asc);
            } else {
                // Previously sorted by GEOLocalisacion, so just reverse.
                sd.Reverse();
            }
        

            // Setting the DataChanged to true results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
              
        }
            
        public virtual void latitudLabel_Click(object sender, EventArgs args)
        {
            //Sorts by latitud when clicked.
              
            // Get previous sorting state for latitud.
        
            OrderByItem sd = this.CurrentSortOrder.Find(GasolineraTable.latitud);
            if (sd == null || (this.CurrentSortOrder.Items != null && this.CurrentSortOrder.Items.Length > 1)) {
                // First time sort, so add sort order for latitud.
                this.CurrentSortOrder.Reset();
                this.CurrentSortOrder.Add(GasolineraTable.latitud, OrderByItem.OrderDir.Asc);
            } else {
                // Previously sorted by latitud, so just reverse.
                sd.Reverse();
            }
        

            // Setting the DataChanged to true results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
              
        }
            
        public virtual void longitudLabel_Click(object sender, EventArgs args)
        {
            //Sorts by longitud when clicked.
              
            // Get previous sorting state for longitud.
        
            OrderByItem sd = this.CurrentSortOrder.Find(GasolineraTable.longitud);
            if (sd == null || (this.CurrentSortOrder.Items != null && this.CurrentSortOrder.Items.Length > 1)) {
                // First time sort, so add sort order for longitud.
                this.CurrentSortOrder.Reset();
                this.CurrentSortOrder.Add(GasolineraTable.longitud, OrderByItem.OrderDir.Asc);
            } else {
                // Previously sorted by longitud, so just reverse.
                sd.Reverse();
            }
        

            // Setting the DataChanged to true results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
              
        }
            
        public virtual void Nombre_GasolineraLabel_Click(object sender, EventArgs args)
        {
            //Sorts by Nombre_Gasolinera when clicked.
              
            // Get previous sorting state for Nombre_Gasolinera.
        
            OrderByItem sd = this.CurrentSortOrder.Find(GasolineraTable.Nombre_Gasolinera);
            if (sd == null || (this.CurrentSortOrder.Items != null && this.CurrentSortOrder.Items.Length > 1)) {
                // First time sort, so add sort order for Nombre_Gasolinera.
                this.CurrentSortOrder.Reset();
                this.CurrentSortOrder.Add(GasolineraTable.Nombre_Gasolinera, OrderByItem.OrderDir.Asc);
            } else {
                // Previously sorted by Nombre_Gasolinera, so just reverse.
                sd.Reverse();
            }
        

            // Setting the DataChanged to true results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
              
        }
            
        public virtual void ObservacionesLabel_Click(object sender, EventArgs args)
        {
            //Sorts by Observaciones when clicked.
              
            // Get previous sorting state for Observaciones.
        
            OrderByItem sd = this.CurrentSortOrder.Find(GasolineraTable.Observaciones);
            if (sd == null || (this.CurrentSortOrder.Items != null && this.CurrentSortOrder.Items.Length > 1)) {
                // First time sort, so add sort order for Observaciones.
                this.CurrentSortOrder.Reset();
                this.CurrentSortOrder.Add(GasolineraTable.Observaciones, OrderByItem.OrderDir.Asc);
            } else {
                // Previously sorted by Observaciones, so just reverse.
                sd.Reverse();
            }
        

            // Setting the DataChanged to true results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
              
        }
            

        // Generate the event handling functions for button events.
        
        // Event handler for ImageButton .
        public virtual void GasolineraDeleteButton_Click(object sender, ImageClickEventArgs args)
        {
        
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();
                
            if (!this.Page.IsPageRefresh) {
        
                this.DeleteSelectedRecords(false);
                this.SetFormulaControls();
          
            }
                this.Page.CommitTransaction(sender);
            } catch (Exception ex) {
                  // Upon error, rollback the transaction
                  this.Page.RollBackTransaction(sender);
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
                DbUtils.EndTransaction();
            }
    
        }
        
        // Event handler for ImageButton .
        public virtual void GasolineraExportExcelButton_Click(object sender, ImageClickEventArgs args)
        {
        
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();
                
            
            // To customize the columns or the format, override this function in Section 1 of the page
            // and modify it to your liking.
            // Build the where clause based on the current filter and search criteria
            // Create the Order By clause based on the user's current sorting preference.
            
                WhereClause wc = null;
                wc = CreateWhereClause();
                OrderBy orderBy = null;
              
                orderBy = CreateOrderBy();
              
              bool done = false;
              string val = "";
              CompoundFilter join = CreateCompoundJoinFilter();
              
              // Read pageSize records at a time and write out the Excel file.
              int totalRowsReturned = 0;


              this.TotalRecords = GasolineraTable.GetRecordCount(join, wc);
              if (this.TotalRecords > 10000)
              {
              
                // Add each of the columns in order of export.
                BaseColumn[] columns = new BaseColumn[] {
                             GasolineraTable.Nombre_Gasolinera,
             GasolineraTable.latitud,
             GasolineraTable.longitud,
             GasolineraTable.GEOLocalisacion,
             GasolineraTable.Descripcion,
             GasolineraTable.Observaciones,
             null};
                ExportDataToCSV exportData = new ExportDataToCSV(GasolineraTable.Instance,wc,orderBy,columns);
                exportData.StartExport(this.Page.Response, true);

                DataForExport dataForCSV = new DataForExport(GasolineraTable.Instance, wc, orderBy, columns,join);

                //  Read pageSize records at a time and write out the CSV file.
                while (!done)
                {
                ArrayList recList = dataForCSV.GetRows(exportData.pageSize);
                if (recList == null)
                break; //we are done

                totalRowsReturned = recList.Count;
                foreach (BaseRecord rec in recList)
                {
                foreach (BaseColumn col in dataForCSV.ColumnList)
                {
                if (col == null)
                continue;

                if (!dataForCSV.IncludeInExport(col))
                continue;

                val = rec.GetValue(col).ToString();
                exportData.WriteColumnData(val, dataForCSV.IsString(col));
                }
                exportData.WriteNewRow();
                }

                //  If we already are below the pageSize, then we are done.
                if (totalRowsReturned < exportData.pageSize)
                {
                done = true;
                }
                }
                exportData.FinishExport(this.Page.Response);
              
              }
              else
              {
              // Create an instance of the ExportDataToExcel class with the table class, where clause and order by.
              ExportDataToExcel excelReport = new ExportDataToExcel(GasolineraTable.Instance, wc, orderBy);
              // Add each of the columns in order of export.
              // To customize the data type, change the second parameter of the new ExcelColumn to be
              // a format string from Excel's Format Cell menu. For example "dddd, mmmm dd, yyyy h:mm AM/PM;@", "#,##0.00"

              if (this.Page.Response == null)
              return;

              excelReport.CreateExcelBook();

              int width = 0;
              int columnCounter = 0;
              DataForExport data = new DataForExport(GasolineraTable.Instance, wc, orderBy, null,join);
                           data.ColumnList.Add(new ExcelColumn(GasolineraTable.Nombre_Gasolinera, "Default"));
             data.ColumnList.Add(new ExcelColumn(GasolineraTable.latitud, "Standard"));
             data.ColumnList.Add(new ExcelColumn(GasolineraTable.longitud, "Standard"));
             data.ColumnList.Add(new ExcelColumn(GasolineraTable.GEOLocalisacion, "Default"));
             data.ColumnList.Add(new ExcelColumn(GasolineraTable.Descripcion, "Default"));
             data.ColumnList.Add(new ExcelColumn(GasolineraTable.Observaciones, "Default"));


              //  First write out the Column Headers
              foreach (ExcelColumn col in data.ColumnList)
              {
              width = excelReport.GetExcelCellWidth(col);
              if (data.IncludeInExport(col))
              {
              excelReport.AddColumnToExcelBook(columnCounter, col.ToString(), excelReport.GetExcelDataType(col), width, excelReport.GetDisplayFormat(col));
              columnCounter++;
              }
              }
              
              while (!done)
              {
              ArrayList recList = data.GetRows(excelReport.pageSize);

              if (recList == null)
              {
              break;
              }
              totalRowsReturned = recList.Count;

              foreach (BaseRecord rec in recList)
              {
              excelReport.AddRowToExcelBook();
              columnCounter = 0;
              foreach (ExcelColumn col in data.ColumnList)
              {
              if (!data.IncludeInExport(col))
              continue;

              Boolean _isExpandableNonCompositeForeignKey = col.DisplayColumn.TableDefinition.IsExpandableNonCompositeForeignKey(col.DisplayColumn);
              if (_isExpandableNonCompositeForeignKey && col.DisplayColumn.IsApplyDisplayAs)
              {
                val = GasolineraTable.GetDFKA(rec.GetValue(col.DisplayColumn).ToString(), col.DisplayColumn, null);
                if (String.IsNullOrEmpty(val))
                {
                  val = rec.Format(col.DisplayColumn);
                }
              }
              else
                val = excelReport.GetValueForExcelExport(col, rec);
              
              excelReport.AddCellToExcelRow(columnCounter, excelReport.GetExcelDataType(col), val);

              columnCounter++;
              }
              }

              // If we already are below the pageSize, then we are done.
              if (totalRowsReturned < excelReport.pageSize)
              {
              done = true;
              }
              }
              excelReport.SaveExcelBook(this.Page.Response);
              }
            
            } catch (Exception ex) {
                  // Upon error, rollback the transaction
                  this.Page.RollBackTransaction(sender);
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
                DbUtils.EndTransaction();
            }
    
        }
        
        // Event handler for ImageButton .
        public virtual void GasolineraImportButton_Click(object sender, ImageClickEventArgs args)
        {
        
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();
                
            } catch (Exception ex) {
                  // Upon error, rollback the transaction
                  this.Page.RollBackTransaction(sender);
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
                DbUtils.EndTransaction();
            }
    
        }
        
        // Event handler for ImageButton .
        public virtual void GasolineraNewButton_Click(object sender, ImageClickEventArgs args)
        {
        
            // The redirect URL is set on the Properties, Custom Properties or Actions.
            // The ModifyRedirectURL call resolves the parameters before the
            // Response.Redirect redirects the page to the URL.  
            // Any code after the Response.Redirect call will not be executed, since the page is
            // redirected to the URL.
            
          string url = @"../Gasolinera/AddGasolinera.aspx";
        
        bool shouldRedirect = true;
        string TargetKey = null;
        string DFKA = TargetKey;
        string id = DFKA;
        string value = id;
      
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();
                
                url = this.ModifyRedirectUrl(url, "",false);
                url = this.Page.ModifyRedirectUrl(url, "",false);
              
            } catch (Exception ex) {
                  // Upon error, rollback the transaction
                  this.Page.RollBackTransaction(sender);
                  shouldRedirect = false;
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
                DbUtils.EndTransaction();
            }
            if (shouldRedirect) {
                this.Page.ShouldSaveControlsToSession = true;
                this.Page.Response.Redirect(url);
            }
        
            else if (TargetKey != null && !shouldRedirect){
            this.Page.ShouldSaveControlsToSession = true ; 
            this.Page.CloseWindow(true);
            }
        
        }
        
        // event handler for Button with Layout
        public virtual void GasolineraSearchButton_Click(object sender, EventArgs args)
        {
              
            try {
                
            this.DataChanged = true;
      
            } catch (Exception ex) {
                  this.Page.ErrorOnPage = true;

            // Report the error message to the end user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
    
            } finally {
    
            }
    
        }
            


        // Generate the event handling functions for filter and search events.
        
        // event handler for FieldFilter
        protected virtual void ID_marcaFilter_SelectedIndexChanged(object sender, EventArgs args)
        {
            // Setting the DataChanged to True results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
            
           				
        }
            
        // event handler for FieldFilter
        protected virtual void Nombre_GasolineraFilter_SelectedIndexChanged(object sender, EventArgs args)
        {
            // Setting the DataChanged to True results in the page being refreshed with
            // the most recent data from the database.  This happens in PreRender event
            // based on the current sort, search and filter criteria.
            this.DataChanged = true;
            
           				
        }
            
      
        // Generate the event handling functions for others
        	  

        private System.Collections.Generic.List<Hashtable> _UIData = new System.Collections.Generic.List<Hashtable>();
        public System.Collections.Generic.List<Hashtable> UIData {
            get {
                return this._UIData;
            }
            set {
                this._UIData = value;
            }
        }
        
        // verify the processing details for these properties
        private int _PageSize;
        public int PageSize {
            get {
                return this._PageSize;
            }
            set {
                this._PageSize = value;
            }
        }

        private int _PageIndex;
        public int PageIndex {
            get {
                // _PageSize return (the PageIndex);
                return this._PageIndex;
            }
            set {
                this._PageIndex = value;
            }
        }

        private int _TotalRecords;
        public int TotalRecords {
            get {
                return (this._TotalRecords);
            }
            set {
                if (this.PageSize > 0) {
                    this.TotalPages = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(value) / Convert.ToDouble(this.PageSize)));
                }
                this._TotalRecords = value;
            }
        }

        private int _TotalPages;
        public int TotalPages {
            get {
                return this._TotalPages;
            }
            set {
                this._TotalPages = value;
            }
        }

        private bool _DisplayLastPage;
        public bool DisplayLastPage {
            get {
                return this._DisplayLastPage;
            }
            set {
                this._DisplayLastPage = value;
            }
        }

        private bool _DataChanged = false;
        public bool DataChanged {
            get {
                return this._DataChanged;
            }
            set {
                this._DataChanged = value;
            }
        }

        private bool _ResetData = false;
        public bool ResetData {
            get {
                return this._ResetData;
            }
            set {
                this._ResetData = value;
            }
        }

        private int _AddNewRecord = 0;
        public int AddNewRecord {
            get {
                return this._AddNewRecord;
            }
            set {
                this._AddNewRecord = value;
            }
        }

        
        private OrderBy _CurrentSortOrder = null;
        public OrderBy CurrentSortOrder {
            get {
                return this._CurrentSortOrder;
            }
            set {
                this._CurrentSortOrder = value;
            }
        }
        
        private GasolineraRecord[] _DataSource = null;
        public  GasolineraRecord[] DataSource {
             
            get {
                return this._DataSource;
            }
            set {
                this._DataSource = value;
            }
        }

#region "Helper Properties"
        
        public System.Web.UI.WebControls.LinkButton DescripcionLabel {
            get {
                return (System.Web.UI.WebControls.LinkButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "DescripcionLabel");
            }
        }
        
        public System.Web.UI.WebControls.ImageButton GasolineraDeleteButton {
            get {
                return (System.Web.UI.WebControls.ImageButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraDeleteButton");
            }
        }
        
        public System.Web.UI.WebControls.ImageButton GasolineraExportExcelButton {
            get {
                return (System.Web.UI.WebControls.ImageButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraExportExcelButton");
            }
        }
        
        public System.Web.UI.WebControls.ImageButton GasolineraImportButton {
            get {
                return (System.Web.UI.WebControls.ImageButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraImportButton");
            }
        }
        
        public System.Web.UI.WebControls.ImageButton GasolineraNewButton {
            get {
                return (System.Web.UI.WebControls.ImageButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraNewButton");
            }
        }
        
        public EnGasAdoAPP.UI.IPaginationMedium GasolineraPagination {
            get {
                return (EnGasAdoAPP.UI.IPaginationMedium)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraPagination");
            }
        }
        
        public System.Web.UI.WebControls.TextBox GasolineraSearch {
            get {
                return (System.Web.UI.WebControls.TextBox)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraSearch");
            }
        }
        
        public EnGasAdoAPP.UI.IThemeButton GasolineraSearchButton {
            get {
                return (EnGasAdoAPP.UI.IThemeButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraSearchButton");
            }
        }
        
        public System.Web.UI.WebControls.Literal GasolineraTitle {
            get {
                return (System.Web.UI.WebControls.Literal)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraTitle");
            }
        }
        
        public System.Web.UI.WebControls.CheckBox GasolineraToggleAll {
            get {
                return (System.Web.UI.WebControls.CheckBox)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GasolineraToggleAll");
            }
        }
        
        public System.Web.UI.WebControls.LinkButton GEOLocalisacionLabel {
            get {
                return (System.Web.UI.WebControls.LinkButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "GEOLocalisacionLabel");
            }
        }
        
        public System.Web.UI.WebControls.DropDownList ID_marcaFilter {
            get {
                return (System.Web.UI.WebControls.DropDownList)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "ID_marcaFilter");
            }
        }
        
        public System.Web.UI.WebControls.Literal ID_marcaLabel {
            get {
                return (System.Web.UI.WebControls.Literal)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "ID_marcaLabel");
            }
        }
        
        public System.Web.UI.WebControls.LinkButton latitudLabel {
            get {
                return (System.Web.UI.WebControls.LinkButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "latitudLabel");
            }
        }
        
        public System.Web.UI.WebControls.LinkButton longitudLabel {
            get {
                return (System.Web.UI.WebControls.LinkButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "longitudLabel");
            }
        }
        
        public System.Web.UI.WebControls.DropDownList Nombre_GasolineraFilter {
            get {
                return (System.Web.UI.WebControls.DropDownList)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "Nombre_GasolineraFilter");
            }
        }
        
        public System.Web.UI.WebControls.LinkButton Nombre_GasolineraLabel {
            get {
                return (System.Web.UI.WebControls.LinkButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "Nombre_GasolineraLabel");
            }
        }
        
        public System.Web.UI.WebControls.Literal Nombre_GasolineraLabel1 {
            get {
                return (System.Web.UI.WebControls.Literal)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "Nombre_GasolineraLabel1");
            }
        }
        
        public System.Web.UI.WebControls.LinkButton ObservacionesLabel {
            get {
                return (System.Web.UI.WebControls.LinkButton)BaseClasses.Utils.MiscUtils.FindControlRecursively(this, "ObservacionesLabel");
            }
        }
        
#endregion

#region "Helper Functions"
        
        public override string ModifyRedirectUrl(string url, string arg, bool bEncrypt)
        {
            return this.Page.EvaluateExpressions(url, arg, bEncrypt, this);
        }
        
        public override string EvaluateExpressions(string url, string arg, bool bEncrypt)
        {
            bool needToProcess = AreAnyUrlParametersForMe(url, arg);
            if (needToProcess) {
                GasolineraTableControlRow recCtl = this.GetSelectedRecordControl();
                if (recCtl == null && url.IndexOf("{") >= 0) {
                    // Localization.
                    throw new Exception(Page.GetResourceValue("Err:NoRecSelected", "EnGasAdoAPP"));
                }

        GasolineraRecord rec = null;
                if (recCtl != null) {
                    rec = recCtl.GetRecord();
                }
                return EvaluateExpressions(url, arg, rec, bEncrypt);
             
            }
            return url;
        }
          
        public virtual int GetSelectedRecordIndex()
        {
            int counter = 0;
            foreach (GasolineraTableControlRow recControl in this.GetRecordControls())
            {
                if (recControl.GasolineraRecordRowSelection.Checked) {
                    return counter;
                }
                counter += 1;
            }
            return -1;
        }
        
        public virtual GasolineraTableControlRow GetSelectedRecordControl()
        {
        GasolineraTableControlRow[] selectedList = this.GetSelectedRecordControls();
            if (selectedList.Length == 0) {
            return null;
            }
            return selectedList[0];
          
        }

        public virtual GasolineraTableControlRow[] GetSelectedRecordControls()
        {
        
            ArrayList selectedList = new ArrayList(25);
            foreach (GasolineraTableControlRow recControl in this.GetRecordControls())
            {
                if (recControl.GasolineraRecordRowSelection.Checked) {
                    selectedList.Add(recControl);
                }
            }
            return (GasolineraTableControlRow[])(selectedList.ToArray(Type.GetType("EnGasAdoAPP.UI.Controls.ShowGasolineraTable.GasolineraTableControlRow")));
          
        }

        public virtual void DeleteSelectedRecords(bool deferDeletion)
        {
            GasolineraTableControlRow[] recordList = this.GetSelectedRecordControls();
            if (recordList.Length == 0) {
                // Localization.
                throw new Exception(Page.GetResourceValue("Err:NoRecSelected", "EnGasAdoAPP"));
            }
            
            foreach (GasolineraTableControlRow recCtl in recordList)
            {
                if (deferDeletion) {
                    if (!recCtl.IsNewRecord) {
                
                        this.AddToDeletedRecordIds(recCtl);
                  
                    }
                    recCtl.Visible = false;
                
                    recCtl.GasolineraRecordRowSelection.Checked = false;
                
                } else {
                
                    recCtl.Delete();
                    // Setting the DataChanged to True results in the page being refreshed with
                    // the most recent data from the database.  This happens in PreRender event
                    // based on the current sort, search and filter criteria.
                    this.DataChanged = true;
                    this.ResetData = true;
                  
                }
            }
        }

        public GasolineraTableControlRow[] GetRecordControls()
        {
            ArrayList recordList = new ArrayList();
            System.Web.UI.WebControls.Repeater rep = (System.Web.UI.WebControls.Repeater)this.FindControl("GasolineraTableControlRepeater");
            if (rep == null){return null;}
            foreach (System.Web.UI.WebControls.RepeaterItem repItem in rep.Items)
            {
                GasolineraTableControlRow recControl = (GasolineraTableControlRow)repItem.FindControl("GasolineraTableControlRow");
                recordList.Add(recControl);
            }

            return (GasolineraTableControlRow[])recordList.ToArray(Type.GetType("EnGasAdoAPP.UI.Controls.ShowGasolineraTable.GasolineraTableControlRow"));
        }

        public new BaseApplicationPage Page 
        {
            get {
                return ((BaseApplicationPage)base.Page);
            }
        }
#endregion

    

    }
  

#endregion
    
  
}

  